⇒ Verifying API Key
While dealing with task data, we need to identify the user using the API key in the request header by reading Authorization field. Basically we’ll look into database for matched API key and get the appropriate user. If the API key not present in users table, then we’ll stop the execution and echo the error json.
11. Add the following method in index.php. The method authenticate() will be executed every time before doing any task related operations on database.
/** * Adding Middle Layer to authenticate every request * Checking if the request has valid api key in the 'Authorization' header */ function authenticate(\Slim\Route $route ) { // Getting request headers $headers = apache_request_headers(); $response = array (); $app = \Slim\Slim::getInstance(); // Verifying Authorization Header if (isset( $headers [ 'Authorization' ])) { $db = new DbHandler(); // get the api key $api_key = $headers [ 'Authorization' ]; // validating api key if (! $db ->isValidApiKey( $api_key )) { // api key is not present in users table $response [ "error" ] = true; $response [ "message" ] = "Access Denied. Invalid Api key" ; echoRespnse(401, $response ); $app ->stop(); } else { global $user_id ; // get user primary key id $user = $db ->getUserId( $api_key ); if ( $user != NULL) $user_id = $user [ "id" ]; } } else { // api key is missing in header $response [ "error" ] = true; $response [ "message" ] = "Api key is misssing" ; echoRespnse(400, $response ); $app ->stop(); } } |
If the api key is missing in the request header, the following json will be echoed with 400 status code.
{ "error" : true , "message" : "Api key is misssing" } |
If the api key is not valid following json will echoed with 401 status code.
{ "error" : true , "message" : "Access Denied. Invalid Api key" } |
Api Calls with Authentication (Including API key in the request)
Following are the API calls should have an Api Key in the request header. These api calls primarily deals the user’s task data like creating, reading, updating and deleting.
Following are the API calls should have an Api Key in the request header. These api calls primarily deals the user’s task data like creating, reading, updating and deleting.
⇒ Creating New Task
12. Add the follwing method to create a new task. Here you can notice that authenticate method is called to verify the Api key before inserting a new task.
/** * Creating new task in db * method POST * params - name * url - /tasks/ */ $app->post( '/tasks' , 'authenticate' , function() use ($app) { // check for required params verifyRequiredParams(array( 'task' )); $response = array(); $task = $app->request->post( 'task' ); global $user_id; $db = new DbHandler(); // creating new task $task_id = $db->createTask($user_id, $task); if ($task_id != NULL) { $response[ "error" ] = false ; $response[ "message" ] = "Task created successfully" ; $response[ "task_id" ] = $task_id; } else { $response[ "error" ] = true ; $response[ "message" ] = "Failed to create task. Please try again" ; } echoRespnse( 201 , $response); }); |
URL | /tasks |
Method | POST |
Params | task |
On successful creation of new task following json will be issued. If you got this json, you can see new row inserted in tasks and user_tasks tables.
{ "error" : false , "message" : "Task created successfully" , "task_id" : 1 } |
⇒ Getting All Tasks
13. Following method will list down all user’s tasks. We don’t have to submit any params for this api call.
/** * Listing all tasks of particual user * method GET * url /tasks */ $app->get( '/tasks' , 'authenticate' , function() { global $user_id; $response = array(); $db = new DbHandler(); // fetching all user tasks $result = $db->getAllUserTasks($user_id); $response[ "error" ] = false ; $response[ "tasks" ] = array(); // looping through result and preparing tasks array while ($task = $result->fetch_assoc()) { $tmp = array(); $tmp[ "id" ] = $task[ "id" ]; $tmp[ "task" ] = $task[ "task" ]; $tmp[ "status" ] = $task[ "status" ]; $tmp[ "createdAt" ] = $task[ "created_at" ]; array_push($response[ "tasks" ], $tmp); } echoRespnse( 200 , $response); }); |
URL | /tasks |
Method | GET |
Params | – |
Following json will be issued for list of tasks. The “tasks” represents list of tasks as an array. Also if the “status” is 0, that means the task is not done yet.
{ "error" : false , "tasks" : [ { "id" : 1 , "task" : "Complete REST article by Sunday" , "status" : 0 , "createdAt" : "2014-01-08 23:35:45" }, { "id" : 2 , "task" : "Book bus tickets!" , "status" : 0 , "createdAt" : "2014-01-08 23:56:52" } ] } |
⇒ Getting Single Task
14. Following method will fetch details of single task. You need to append the task id with a / to url. For an example if you want details of task 15, the url will be /tasks/15.
/** * Listing single task of particual user * method GET * url /tasks/:id * Will return 404 if the task doesn't belongs to user */ $app->get( '/tasks/:id' , 'authenticate' , function($task_id) { global $user_id; $response = array(); $db = new DbHandler(); // fetch task $result = $db->getTask($task_id, $user_id); if ($result != NULL) { $response[ "error" ] = false ; $response[ "id" ] = $result[ "id" ]; $response[ "task" ] = $result[ "task" ]; $response[ "status" ] = $result[ "status" ]; $response[ "createdAt" ] = $result[ "created_at" ]; echoRespnse( 200 , $response); } else { $response[ "error" ] = true ; $response[ "message" ] = "The requested resource doesn't exists" ; echoRespnse( 404 , $response); } }); |
URL | /tasks/id (id should be replaced with task id) |
Method | GET |
Params | – |
The details of a single task will be in following json format.
{ "error" : false , "id" : 2 , "task" : "Book bus tickets!" , "status" : 0 , "createdAt" : "2014-01-08 23:56:52" } |
If you pass a task id which is not there in the database, you will get 404 not found error.
⇒ Updating Task
15. Following code will take care of updating a task. The url for this api call is same as getting the details of single task, only difference is we should use PUT method instead of GET.
/** * Updating existing task * method PUT * params task, status * url - /tasks/:id */ $app ->put( '/tasks/:id' , 'authenticate' , function ( $task_id ) use ( $app ) { // check for required params verifyRequiredParams( array ( 'task' , 'status' )); global $user_id ; $task = $app ->request->put( 'task' ); $status = $app ->request->put( 'status' ); $db = new DbHandler(); $response = array (); // updating task $result = $db ->updateTask( $user_id , $task_id , $task , $status ); if ( $result ) { // task updated successfully $response [ "error" ] = false; $response [ "message" ] = "Task updated successfully" ; } else { // task failed to update $response [ "error" ] = true; $response [ "message" ] = "Task failed to update. Please try again!" ; } echoRespnse(200, $response ); }); |
URL | /tasks/id (id should be replaced with task id) |
Method | PUT |
Params | task, status (0 or 1) |
Upon successful updation you will get following json.
{ "error" : false , "message" : "Task updated successfully" } |
⇒ Deleting Task
16. Again delete task url is same as update task, but this requires DELETE method.
/** * Deleting task. Users can delete only their tasks * method DELETE * url /tasks */ $app->delete( '/tasks/:id' , 'authenticate' , function($task_id) use($app) { global $user_id; $db = new DbHandler(); $response = array(); $result = $db->deleteTask($user_id, $task_id); if ($result) { // task deleted successfully $response[ "error" ] = false ; $response[ "message" ] = "Task deleted succesfully" ; } else { // task failed to delete $response[ "error" ] = true ; $response[ "message" ] = "Task failed to delete. Please try again!" ; } echoRespnse( 200 , $response); }); |
URL | /tasks/id (id should be replaced with task id) |
Method | DELETE |
Params | – |
You will get following json if the task is deleted successfully.
{ "error" : false , "message" : "Task deleted succesfully" } |
Here we completes the PHP and MySQL part. Now it’s time to move on to testing the API just to make sure that whatever code we have written is working.
Testing the API
Following is the list of URL we need to test using Chrome Advanced REST client extension with possible combinations of inputs.
URL | Method | Parameters | Description |
http://localhost/task_manager/v1/register | POST | name, email, password | User registration |
http://localhost/task_manager/v1/login | POST | email, password | User login |
http://localhost/task_manager/v1/tasks | POST | task | To create new task |
http://localhost/task_manager/v1/tasks | GET | Fetching all tasks | |
http://localhost/task_manager/v1/tasks/:id | GET | Fetching single task | |
http://localhost/task_manager/v1/tasks/:id | PUT | Updating single task | |
http://localhost/task_manager/v1/tasks/:id | DELETE | task, status | Deleting single task |
The following video shows you how to test the API thoroughly.
0 comments:
Post a Comment