2016年10月5日 星期三

How to create REST API for Android app using PHP, Slim and MySQL – Day 1/2

Ref : http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/


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.
If you consider EvernoteWunderlist apps, these apps can uninstalled at anytime and once we install them back and login, all our data will be restored. This is because all the data will stored in a cloud database and communication b/w app and database will be done using a REST API.
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.

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.
GETTo fetch a resource
POSTTo create a new resource
PUTTo update existing resource
DELETETo 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 restapitutorial.com and Wikipedia
200OK
201Created
304Not Modified
400Bad Request
401Unauthorized
403Forbidden
404Not Found
422Unprocessable Entity
500Internal Server Error
» URL Structure
In REST design the URL endpoints should be well formed and should be easily understandable. Every URL for a resource should be uniquely identified. If your API needs an API key to access, the api key should be kept in HTTP headers instead of including it in URL.
For an example:
GET http://abc.com/v1/tasks/11 – Will give the details of a task whose id is 11
POST http://abc.com/v1/tasks – Will create a new task
» API Versioning
There is a huge discussion on API versioning whether to maintain api version in the URL or in the HTTP request headers. Even though it is recommended that version should be included in the request headers, I feel comfortable to maintain it in the URL itself as it is very convenient on the client side to migrate from one version to another.
Example:
http://abc.com/v1/tasks
http://abc.com/v2/tasks
» 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. This article Designing a Secure REST (Web) API without OAuth by Riyad Kalla covers the best way to secure you rest api. But as this article aims at very beginners I am not going with any complex model. So for now we can go with generating a random api key for every user. 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.
Authorization: bf45c093e542f057caee68c47787e7d6
More Knowledge on REST API Design
Following links will explains you the best practices of REST and other principles.
1. RESTful Web services: The basics
2. Stackoverflow discussion
3. A video presentation about REST+JSON API Design – Best Practices for Developers by Les Hazlewood, Stormpath

2. Prerequisite

Before diving deep into this article, it is recommended that you have basic knowledge on PHP, MySQL, JSON parsing and Android PHP, MySQL communication. Go through following links to get basic knowledge.

3. Slim PHP Micro 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 (download the stable release) and keep it aside. We are gonna need this some point later after doing required setup.

4. Installing WAMP Server (Apache, PHP and MySQL)

WAMP lets you install ApachePHP and MySQL with a single installer which reduces burden of installing & configuring them separately. Alternatively you can use XAMPLAMP (on Linux) and MAMP (on MAC). WAMP also provides you phpmyadmin to easily interact with MySQL database.
Download & install WAMP from http://www.wampserver.com/en/. Choose the correct version which suits your operating system (32bit or 64bit). Once you have installed it, open the program from Start -> All Programs -> Wamp Server -> Start WampServer.
Open http://localhost/ and http://localhost/phpmyadmin/ to verify WAMP is installed successfully or not.

5. Installing Chrome Advanced REST client extension for Testing

Chrome Advanced REST client extension provides an easy way to test the REST API. It provides lot of options like adding request headers, adding request parameters, changing HTTP method while hitting an url. Install Advanced REST client extension in chrome browser. Once you installed it you can find it in chrome Apps or an icon at the top right corner.

6. REST API for Task Manager App

To demonstrate REST API I am considering an example of Task Manager 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
URLMethodParametersDescription
/registerPOSTname, email, passwordUser registration
/loginPOSTemail, passwordUser login
/tasksPOSTtaskTo create new task
/tasksGETFetching all tasks
/tasks/:idGETFetching single task
/tasks/:idPUTUpdating single task
/tasks/:idDELETEtask, statusDeleting 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 userstasks 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.


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 task_manager;
 
USE task_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  `task_manager`.`users` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
 
ALTER TABLE  `user_tasks` ADD FOREIGN KEY (  `task_id` ) REFERENCES  `task_manager`.`tasks` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;








沒有留言:

張貼留言