2014-01-20

The previous day How to create REST API for Android app using PHP, Slim and MySQL – Day ⅓, we have learned fundamental concepts about REST API and preparing your development environment ready by installing the required tools needed. I hope everyone got good knowledge about REST and other technical areas. Also I am assuming that you got all the required tools installed.

Today we are going to learn how to setup a PHP project and writing the actual code for REST API. Also we’ll learn writing necessary SQL queries to perform database CRUD operations.

DOWNLOAD CODE



8. Starting PHP Project

As we all know IDEs make development process easier. So I recommend you use an IDE for developing the PHP project instead of using plain notepad. You can go for Eclipse, Aptana Studio, PhpStorm or Netbeans. But I personally felt very comfortable using Netbeans for PHP projects.

PHP Project directory structure
The following diagram will give you an idea about the directory structure of the project which we are going to develop now.



libs – All the third party libraries goes here. In our case we place Slim library here
include – All the helpers classes we build placed here
index.php – Takes care of all the API requests
.htaccess – Rules for url structure and other apache rules

Now let’s start the PHP project

1. Go to the directory where WAMP is installed. In general wamp will be installed in C:\wamp. (If you have installed any other software rather than WAMP, you should go to the directory recommended by that software).

2. As a first step we start with creating required directories. Inside wamp folder go to www folder (c:\wamp\www\) and create a folder named task_manager. This folder will be the parent directory of our project. Inside task_manager create two more folders named libs and include.

3. Now the paste the Slim library inside libs folder. The download link for Slim is provided in previous part.

4. Normally Slim framework works when index.php includes in the url which makes url not well-formed. So using the .htacess rules we can get rid of index.php from the url and make some friendly urls. Inside task_manager folder create a file named .htaccess and paste the following code. (Note that this file name shouldn’t include any additional extension in the name like .txt)

8.1 Preparing Helper Classes

First we start writing set of helper classes required in this project. These helper classes provides necessary functions required to interact with the database.

5. Inside include folder create file named Config.php with following content. This file contains the entire project configuration like database connection parameters and other variables.

6. Create another class named DbConnect.php This class file mainly takes care of database connection.

Encrypting the password
7. The best way to secure the user passwords is not store them as plain text, instead all the passwords should be encrypted before storing in db. The following class takes care of encrypting the user password. Create another file named PassHash.php and paste the following code.

8. Now create another class named DbHandler.php This class is one of the important files in our project which provides necessary functions to perform CRUD operations on the database. Every function is self explanatory by it’s name and comments, I don’t have to have to explain much about them.

8.2 Handling the API calls

Now we have all the required classes for the REST API. Now we can start the code to handle all individual api calls.

8. Inside task_manger folder create another folder named v1. Inside v1 folder create a file named index.php and add the following code. Here we are including required libraries and other helper functions.

verifyRequiredParams() – This function verifies the mandatory parameters in the request.
validateEmail() – Verifies whether email address is valid one or not.
echoRespnse() – This function will echo the JSON response with a status code.

The JSON response

On calling every API request a JSON response will be issued with a HTTP status code. On the client side you have to verify the response http status code. If the status is 200, the request is processed successfully. Also you can notice a “error” node in the response. If the error value is true, that means some error occurred while processing the user data.

Api Calls without Authentication (without API key in the request header)

These calls don’t have to include Api Key in the request header. The main purpose of these calls is to interact with database without any authentication. User registration and login comes under this category.

⇒ User Registration

In order to interact with the API, the user has to register in our system first. Once he registered an API key will be generated and stored in the database. This API key will be private to that user only.

9. Add the following code in index.php. This function handles user registration.

In the following table you can find the API request information about the URL, HTTP method and the parameters needed to be posted.

URL

/register

Method

POST

Params

name, email, password

Upon the successful registration the following json response will be issued.

If the request is missing mandatory parameters the following json will be issued.

⇒ User Login

10. Add the following code to handle user login. After verifying user credentials, the API Key for that user will be issued in the json response. The api key should be included in the request header in all remaining api calls.

URL

/login

Method

POST

Params

email, password

On successful login the following json will be issued.

If the credentials are wrong, you can expect the following json.

⇒ 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.

If the api key is missing in the request header, the following json will be echoed with 400 status code.

If the api key is not valid following json will echoed with 401 status code.

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.

⇒ 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.

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.

⇒ 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.

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.

⇒ 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.

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.

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.

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.

⇒ Deleting Task

16. Again delete task url is same as update task, but this requires DELETE method.

URL

/tasks/id (id should be replaced with task id)

Method

DELETE

Params

-

You will get following json if the task is deleted successfully.

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.

REST API Testing

If all your API urls working as shown in the video, we can move forward to our next step i.e deploying the API on a server. So that everybody can access the API from anywhere. The third part covers the process of hosting the services online.

Show more