If you are going to build an android application (it can be any other mobile platform or web too) that manages all the user data on a central database, REST API will be good architectural option to do the communication between the app and the server. This tutorial gives enough knowledge about building a REST API for very beginners. As this tutorial seems lengthy, I had divided it into 2 parts. In the 1st part we learn fundamental concepts of REST and do the required setup. In the 2nd part building actual API (writing PHP & MySQL code) is covered.
VIDEO DEMO
1. Basics of REST API Design
REST architecture will be useful to build client/server network applications. REST represents Representational State Transfer. Implementing REST is very simple compared to other methods like SOAP, CORBA, WSDL etc., It basically works on HTTP protocol.
Following are the list of things should be considered while building a REST API
» HTTP Methods
A well-designed Restful API should support most commonly used HTTP methods (GET, POST, PUT and DELETE). There are other HTTP methods like OPTIONS, HEAD but these are used most often. Each method should be used depending on the type of operation you are performing.
- GET – To fetch a resource
- POST – To create a new resource
- PUT – To update existing resource
- DELETE – To delete a resource
» HTTP Status Code
HTTP status codes in the response body tells client application what action should be taken with the response. For an example if the response code 200, it means on the server side the request is processed successfully and you can expect updated data in the response. As well if the status code is 401, the request is not authorized. An example cause for 401 could be API key is invalid.
It is not necessary to support all HTTP status codes, but supporting at least the following codes should be good enough. Check out list of HTTP codes from Here
- 200 – OK
- 201 – Created
- 304 – Not Modified
- 400 – Bad Request
- 401 – Unauthorized
- 403 – Forbidden
- 404 – Not Found
- 422 – Unprocessable Entity
- 500 – Internal Server Error
» Content Type
The Content Type in HTTP headers specifies the kind of the data should be transferred between server and client. Depending upon the data your API supporting you need to set the content type.
For an example, JSON Mime type should be Content-Type: application/json, for XML Content-Type: application/xml. You can find list of supported MIME Types Here
» API Key
If you are building a private API where you want to restrict the access or limit to a private access, the best approach is to secure your API using an API key. The user is identified by the API key and all the actions can be performed only on the resources belongs to him.
The API key should be kept in request header Authorization filed instead of passing via URL.
2. Prerequisite
Before diving deep into this article, it is recommended that you have basic knowledge on PHP, MySQL, JSON Parsing, PHP and MySQL. Go through following links to get basic knowledge.
1. PHP Basics
2. MySQL Prepared Statements
3. Android JSON Parsing
3. Slim Framework
Instead of start developing a fresh REST framework from scratch, it is better go with a already proven framework. Then I came across Slim framework and selected it for the following reasons.
1. It is very light weight, clean and a beginner can easily understand the framework.
2. Supports all HTTP methods GET, POST, PUT and DELETE which are necessary for a REST API.
3. More importantly it provides a middle layer architecture which will be useful to filter the requests. In our case we can use it for verifying the API Key.
Downloading Slim Framework
Download the Slim framework from Here and keep it aside. We are gonna need this some point later after doing required setup.
4. Installing XAMPP Server (Apache, PHP and MySQL)
Download & Install XAMPP server from https://www.apachefriends.org/download.html. Once installed, launch the XAMPP control panel and Start Apache and MySQL.
You can test your server by opening the address http://localhost/ in your browser. Also you can check phpmyadmin by opening http://localhost/phpmyadmin
5. Installing POSTMAN
Postman is a great tool when trying to dissect RESTful APIs made by others or test ones you have made yourself. It offers a sleek user interface with which to make HTML requests, without the hassle of writing a bunch of code just to test an API’s functionality.
To install Postman, go to the This Link and click Download for Mac / Windows / Linux depending on your platform.
6. Creating TODO List REST API
To demonstrate REST API I am considering an example of TODO List App with very minimal functionalities.
1. User related operations like registration and login
2. Task related operations like creating, reading, updating and deleting task. All task related API calls should include API key in Authorization header field.
Following are the list of API calls we are going to build in this tutorial. You can notice that same URL endpoint is used for multiple API calls, but the difference is the type of HTTP method we use to hit the URL. Suppose if we hit /tasks with POST method, a newer task will be created. As well if we hit /tasks with GET method, all the tasks will be listed.
API URL Structure
URL | Method | Parameters | Description |
/register | POST | name, email, password | User Registration |
/login | POST | email, password | User Login |
/tasks | POST | task | To Create New Task |
/tasks | GET | Fetching all Tasks | |
/tasks/:id | GET | Fetching Single Task | |
/tasks/:id | PUT | Updating Single Task | |
/tasks/:id | DELETE | task, status | Deleting Single Task |
7. Creating MySQL Database
For this app we don’t need a complex database design. All we need at this stage is only three tables. You can always add few more tables if you want to extend the functionality. I have created three tables users, tasks and user_tasks.
users – All user related data will be stored here. A row will inserted when a new user register in our app.
tasks – All user tasks data will be stored in this table
user_tasks – Table used to store the relation between user and his tasks. Basically we store users id and task id in this table.
users – table to store users data
Field | Type | Key |
id | INT | PK |
name | VARCHAR | |
VARCHAR | ||
password_hash | TEXT | |
api_key | VARCHAR | |
status | INT | |
created_at | TIMESTAMP |
tasks – table to store tasks data
Field | Type | Key |
id | INT | PK |
task | TEXT | |
status | INT | |
created_at | TIMESTAMP |
user_tasks – Relation between users and tasks tables
Field | Type | Key |
id | INT | PK |
user_id | INT | FK |
task_id | INT | FK |
Open the phpmyadmin from http://localhost/phpmyadmin and execute the following SQL queries. As well if you are familiar with phpmyadmin, you can use phpmyadmin graphical interface to create tables.
CREATE DATABASE todo_list_manager; USE todo_list_manager; CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(250) DEFAULT NULL, `email` varchar(255) NOT NULL, `password_hash` text NOT NULL, `api_key` varchar(32) NOT NULL, `status` int(1) NOT NULL DEFAULT '1', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ); CREATE TABLE IF NOT EXISTS `tasks` ( `id` int(11) NOT NULL AUTO_INCREMENT, `task` text NOT NULL, `status` int(1) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ); CREATE TABLE IF NOT EXISTS `user_tasks` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `task_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `user_id` (`user_id`), KEY `task_id` (`task_id`) ); ALTER TABLE `user_tasks` ADD FOREIGN KEY ( `user_id` ) REFERENCES `todo_list_manager`.`users` ( `id` ) ON DELETE CASCADE ON UPDATE CASCADE ; ALTER TABLE `user_tasks` ADD FOREIGN KEY ( `task_id` ) REFERENCES `todo_list_manager`.`tasks` ( `id` ) ON DELETE CASCADE ON UPDATE CASCADE ;
After executing these queries go through each tables and make sure that everything created correctly.
Until now we are done with getting your system ready for development. The next article How to create REST API for Android app using PHP, Slim and MySQL – Part 2/2 covers the overall process of starting and finishing the PHP and MySQL project.
Happy Coding 😀
Yash Pawar
Yash is hardcore programmer and programming has been his passion since he compiled his first hello-world program. Solving real problems of developers through tutorials has always been interesting part for him.