How to create REST API for Android app using PHP, Slim and MySQL – Day 1/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 Evernote, Wunderlist 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.

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 restapitutorial.com and Wikipedia

200

OK

201

Created

304

Not Modified

400

Bad Request

401

Unauthorized

403

Forbidden

404

Not Found

422

Unprocessable Entity

500

Internal 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 Apache, PHP and MySQL with a single installer which reduces burden of installing & configuring them separately. Alternatively you can use XAMP, LAMP (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.

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.

Alternatively if you prefer using firefox, you can go for Poster add-on to test the API.

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

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info

Very nice tutorial ravi, i have a question regarding a security issue:
1) How can i handle an expiration date for the api-key? because if i store the api-key in SharedPreferences and send the api_key everytime with the request, the user will be forever logged in

I am confused! Why I need the slim framework and if it must, how can i create one for myself. Please also guide me through the android app code (I already know the “Connecting sql to android” part.

Pawan

please reply to my question

Mich

Hi,
First thank you for the tutorial it’s really great.

I try to test the REST API but I’ve got some problems.
I work on LAMP (Debian), I download the source from you website (thanks) but when I try to test with Advanced Rest Client I’ve got the 404 error

If you have some ideas about where is the problem I’ll be very grateful

Thank you, Have a nice day

Mich

up

Mich

I download sources and I follow video instructions for test the API but I always got a 404 Error.
I try to copy another file “index.html” in /task_manager/v1/ and it works.

I try to modify .htaccess as ‘Tom L.’ has advised (in the 2/2 page of tutorial) but I’ve got the same bad result
Is there some modifications that we have to do to use source on Linux installation ?
(Informations: Debian=7.6, Php=5.4.4, Apache=2.2.22, MySQL=5.5.38)

Thank you

Paulo Gomes

Hi. Did you solve this 404 error problem?

thanks,
Paulo Gomes

Andrew Nyago

i’m havng the sameproblemright now/
do we need to restar tour compters?

Tal

Hi, I still have tried it yet but can you please explain how to do a multipart-data method? a simple example for the register method with a profile image would be great!
Thank you for all these tutorials,especially for image caching!

Enti

Ravi, what are advantages/disadvantages of Slim framework over other more popular solutions like Restlet and Spring? Why did you chose Slim? Thank you

LordLiverpool

Your download code button isn’t working 🙁

3dryan

I appreciate the tutorial. Using the mysql native driver really caused me fits though. I couldn’t (and still can’t) get it working under MAMP or AMPPS, so I re-wrote all the database handler stuff using PDO.

Ron

Hello,

Thank you for the tutorial Ravi.

Is there somebody succeed to run the code on LAMP ?
If you have advice to do it, I would be grateful… sorry if it’s stupid but I’m a noob :s

Actually, I am developing an app to upload a file from android phone to a remote server which needs authentication. UploadToServer.php file is present in that server which helps in receiving the file from the phone and stores in the server in required path. But to run this php file from the URL in the app, authentication must be given to the app.

I would like to know how to provide this authentication (login details) to the URL (to run php file in server) present in my android app. Normally in various blogs, I can only see examples without authentication.

Thanks you very much,
Raj Bharath

Srishti

Hi ravi,wonderful work,could you tell me how to deploy rest api in the market ,means where from to buy domain,,any help would be great..

Vamos

I want to use a REST api (for example the above api) in my php script for my website.How do I call them for registering users like in forms using $_POST ?

Thanks Ravi for this tutorial really helpful, great job ! I use it for a AngularJs app. I just had some problems to get my json data with $http.get() method in my angular controller, the result retrieve from the URL of the API was empty. If someone have the same problem, you can correct it adding the following line in the echoRespnse function :
$app->response->headers->set(‘Access-Control-Allow-Origin’, ‘*’);

Link not working any more, anyone please could give me alternative link or if u have a copy for the article 🙁

Riccardo Bella

Hi Ravi. I did a guide in italian and used some piece of your code.
Obviously i cited you every where (link and name) and left the “by ravi tamada” in comments. I hope you are ok with this (anyway, if you want I delete any part of your code!)
If you want a link to see if you like as I used your code, I will write, I don’t want to use your post as a place for my links!
Thansk a lot for your work!

It was so great that you have mentioned my name. Actually I don’t mind if you don’t mention too or use the code in any manner.

All the best.

Nasir Hasanov

Hi Ravi ..Thanks for this awesome tutorials… I just wanted to ask , can i use this API skeleton for a social app?

Arish

any tutorial here for gprs tracking between admin and clients

Jorge 27

Thanks for the great job!

Nivaskannan

Can you please elaborate the same with oracle pl/sql

ssv

REST API working perfectly at localhost but inside the remote shared server godaddy did’t work the responses how to correct that one??

Ritshi Netshiavela

Thank You Ravi. This tutorial is awesome

Ramose

I run Register api in Advance Rest Client and Postman. The result always 404. I have open access in httpd.conf configuration file. How to solve this? Thanks.

Ramose

Solved. I download the source files and it works. It’s look like a dot differences between my own files and donwloaded files that caused it 404 before.
Really helpful tutorial, Ravi. Thanks.

vinod

how to create REST full java mysql weservices in android…

Ivonne Jackson

The app does not give me error but I do not charge products. Try to link it with my hosting I think that’s where the error occurs. Please help.

pedrish

hi dear ravi it is working very well in local host but i get 500 iternal server error in live server . should i change .htaccess file in live server ?

Reza Khan

hello ravi sir, thanks for the great tutorial. i understood how to use this api from Chrome extension. But i don’t get how to implement this on android app. I mean, how can I send the field data or the parameter data through the link? there is no option to send the required field data through the link….. can you help with this? thanks in advance 🙂

We are outsourcing mobile app development and concerned about live database security.
For development purpose we had shared dummy data with app team. Now since development is done, as per discussion with app team we have decided to maintain config file with RESTful api.
Can you please help me with how this can be achieved without harming security of our database.

Slim is a microframework in which you won’t get much benefits. However if you want to secure your mysql credentials, you can keep them in a .env file and mention the database credentials there. And don’t give this file to your developers, instead ask them to create the same file with another mysql credentials. In production, you can remove the mysql dummy users.

Also if you are seriously involved in app development, I suggest you go through Laravel as it is highly architectural.

Ken Choong

Hi Ravi,me again..I just wonder why I should create the 3rd table which is `user_task` which is storing all ID in 3 table in this table.What is the main purpose for doing so?And what will happen if not do so??

Ken Choong

Once again,what is the usage for `status` column for the both user table and task table?What is it usage?what is the default value 1 in user table,and 0 in task table stand for??Can guide me for the right direction??

Hello Please how do i get my android app to use the rest api because my authentication is written in twitter digits, how do i get it to consume the rest api help

Matiss

i, hope you can help me. I get the error

bHandler.php
404 Page Not Foundbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}404 Page Not FoundThe page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.Visit the Home Page

Does anyone know how to solve this?
Best,
Matiss

abdul

hi, please tell me onething. i coded as per your instructions but while testing post method it is receiving null.

Reza Khan

Hello Ravi Sir, thanks for this great tutorial. but whenever I try to use register API, it returns “{
“error”: true,
“message”: “Email address is not valid”
}” though I’m providing valid email address. Can you help me with that?

Kishan Kant Kataria

I love all your tutorials, basically i learned android following your tutorials, you are a legendary developer with very deep knowledge about what you do and what you write in your tutorials thanks alot once again man Hats off!!

hero

Thanks for the great tutorial on setting up REST API. I was able to fire all the requests using ARC client however when I use any other client like post or proxy tool. I get api key is missing. It will be great to know if app will only work on specific clients.

Not necessarily. You can maintain them separately and include all files in index.php. Read the Slim docs for more info.

Huzaifa

Hi , Can you tell me if is there any changes needs to be made when putting it online?

Abhishek shrivastava

Can u please tell me how to specify cache-control in header in slim?

IT 部門看護銀行

Hi, I’m getting error with 500 error code in …/task_manager/v1/tasks (GET) from my online server.
The others are working fine. That “/v1/tasks” GET part actually has no problem in localhost, but matter in the online one.

I got solution from hosting admin,
The error was caused by the mysql & mysqli.
It was fixed by changing it to nd_mysql & nd_mysqli in php selector, then disable the previous one. No code error. Purely from hosting side only.