How to Build a Restful API

How to build a REST API without resource?

For a start assuming you are fine with any language, here you can find discussion about implementing a web service to upload file. Here is an actual script to implement upload function.

EDIT:

When you cannot visualize the provides service as a resource you can name them verbs(But most of the REST api provide resources). For example you can find twitter api with services like destroy and echonest api with services like upload etc,. Here is a best practice blog for uri design.

How to build a RESTful API?

Here is a very simply example in simple php.

There are 2 files client.php & api.php. I put both files on the same url : http://localhost:8888/, so you will have to change the link to your own url. (the file can be on two different servers).

This is just an example, it's very quick and dirty, plus it has been a long time since I've done php. But this is the idea of an api.

client.php

<?php

/*** this is the client ***/

if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information
{
$user_info = file_get_contents('http://localhost:8888/api.php?action=get_user&id=' . $_GET["id"]);
$user_info = json_decode($user_info, true);

// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<table>
<tr>
<td>Name: </td><td> <?php echo $user_info["last_name"] ?></td>
</tr>
<tr>
<td>First Name: </td><td> <?php echo $user_info["first_name"] ?></td>
</tr>
<tr>
<td>Age: </td><td> <?php echo $user_info["age"] ?></td>
</tr>
</table>
<a href="http://localhost:8888/client.php?action=get_userlist" alt="user list">Return to the user list</a>
<?php
}
else // else take the user list
{
$user_list = file_get_contents('http://localhost:8888/api.php?action=get_user_list');
$user_list = json_decode($user_list, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<ul>
<?php foreach ($user_list as $user): ?>
<li>
<a href=<?php echo "http://localhost:8888/client.php?action=get_user&id=" . $user["id"] ?> alt=<?php echo "user_" . $user_["id"] ?>><?php echo $user["name"] ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php
}

?>

api.php

<?php

// This is the API to possibility show the user list, and show a specific user by action.

function get_user_by_id($id)
{
$user_info = array();

// make a call in db.
switch ($id){
case 1:
$user_info = array("first_name" => "Marc", "last_name" => "Simon", "age" => 21); // let's say first_name, last_name, age
break;
case 2:
$user_info = array("first_name" => "Frederic", "last_name" => "Zannetie", "age" => 24);
break;
case 3:
$user_info = array("first_name" => "Laure", "last_name" => "Carbonnel", "age" => 45);
break;
}

return $user_info;
}

function get_user_list()
{
$user_list = array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel")); // call in db, here I make a list of 3 users.

return $user_list;
}

$possible_url = array("get_user_list", "get_user");

$value = "An error has occurred";

if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
{
switch ($_GET["action"])
{
case "get_user_list":
$value = get_user_list();
break;
case "get_user":
if (isset($_GET["id"]))
$value = get_user_by_id($_GET["id"]);
else
$value = "Missing argument";
break;
}
}

exit(json_encode($value));

?>

I didn't make any call to the database for this example, but normally that is what you should do. You should also replace the "file_get_contents" function by "curl".

In making a RESTful api, is there a recommended way to handle route syntax involving multiple queries?

REST doesn't care what spelling conventions you use for your resource identifiers. As long as your spellings are consistent with the production rules described by RFC 3986, you're fine.

If you have a lot of similar resources, it can be convenient to use URI Templates and variable expansion to define your family of identifiers. That allows clients to use general purpose libraries to construct your identifiers, and allows you the option of using a general purpose library to parse information out of the target URI for each request.

Beyond some purely mechanical concerns (ex: using the proper escape sequences), it really doesn't matter whether you use variable expansion in the query, or in path segments, or multiple times in each, or whatever.

There are trade offs to consider -- path segments combine well with relative resolution; application/x-www-form-urlencoded key value pairs combine well with HTML forms.

Beyond that, the machines don't care. So choose any spelling that makes things easier for some people that you care about.

Building a RESTful API with high scalability

It is doable in Go and it is doable in Node. It is doable in other languages like Erlang or Python as well. But since you're asking about Node then this is what I'll answer about.

The most important thing for high concurrency in Node is to never block the event loop or do any blocking operation ever (unless it's the first tick of the event loop). This is the number one thing that people do and ruin the concurrency - like putting a little innocent-looking fs.statSync() now and then (see this answer for examples of such mistakes right in the answers on Stack Overflow). Using any blocking operation (including long running for or while loop) after the first tick is always a mistake and in fact I think it should throw exceptions.

Another thing that while not being an outright mistake in all situations may still harm the scalability is storing any state in your application. If you need to have any persistent state (and try to minimize that need at all cost) then you should use a database for that. For data that needs to be shared between requests quickly like session data you should use a fast database like Redis, but only if you cannot achieve the same with things like JWT etc.

Prefer horizontal instead of vertical scalability, because at some point there will be no bigger server, but there will always be more servers.

To sum it up:

  1. Never block the event loop
  2. Do all CPU-heavy computations in external processes
  3. Never block the event loop
  4. Use Redis or Memcached for shared state
  5. Never block the event loop
  6. Use clustering for horizontal scalability
  7. Never block the event loop

Did I mention never blocking the event loop?

How To Build RESTful APIs Using PHP and Laravel

defining routes changes depending on the version of Laravel.

In Laravel 5.3 we can define api in a separate api.php file instead of the routes.php file.

I can say a few basic points which will help for REST API.

  1. Authentication :

    You can use auth_token in your backend (database) and on successful login update the auth token and in every api request you should pass the auth token. This will match with the auth token in the backend if it is same then we will let the user to get data response.

  2. Route:

    It is same as we are defining routes in laravel routes.php file. But it is good to prefix it like this.

    Route::group(['prefix' => 'api/v1'], function()
    {
    Route::post('authenticate', 'APIV1Controller@authenticate');
    }

    Using this you can group the routes and it is good to maintain versions ( v1 ) so that we can update api by maintaining different versions like v2.

  3. REST API CLIENT:

    You can use postman or the REST API Client addon for Firefox to hit the API.

  4. Headers:

    To hit the API we need to specify headers. To pass JSON request, the header should be

    Content-Type: application/json
  5. Always have status_code and message in your api response. The response should be return in JSON Format.

    Simple Example :

    routes.php

    Route::group(['prefix' => 'api/v1'], function()
    {
    Route::post('getUserData', 'APIV1Controller@getUserData');
    }

    APIV1Controller.php

    public function getUserData(Request $request){

    $user = User::select('name','phone')
    ->where('email','=',$request['email'])->first();
    if($user){
    return response()->json(['statusCode' => '200','message' => 'User Found','userDetails'=>$user]);
    }
    else{
    return response()->json(['statusCode' => '400','message' => 'User Not Found']);
    }
    }

    In Postman:

    URL : www.example.com/api/v1/getUserData

    Headers: Content-Type: application/json

    Request : {"email":"mytest@test.com"}

    Hit the api and you will get the response.

    Response :

    {"statusCode":"200","message":"User Found","userDetails":{"name":"Ganesh","phone":"1525353535"}}


Related Topics



Leave a reply



Submit