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.

android rest api php mysql slim

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.

android rest api php mysql architecture

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.


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

1. PHP Basics
2. MySQL Prepared Statements
3. Android JSON Parsing
4. How to connect Android with PHP, MySQL

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.

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.

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

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

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.

android rest api mysql database design

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;

  `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`)

  `task` text NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)

  `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` (

ALTER TABLE  `user_tasks` ADD FOREIGN KEY (  `task_id` ) REFERENCES  `task_manager`.`tasks` (

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 – Day 2/2 covers the overall process of starting and finishing the PHP and MySQL project.

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
  • Andre McCalla

    I am so looking forward to the next article. This is looking very interesting

  • MrNet

    It’s useful, thanks.

  • Selva

    Very useful and nice presentation.

  • Mohammed Saudi

    Thanks for your great articles and projects all over androidhive.info

  • Kristijan Drača

    Awesome article! I’m relay looking forward for next one!

  • Good article. Looking forward to the next one.

  • Devi

    Nice Article,very interesting…..and waiting for the next one…… πŸ™‚

  • Nice one

  • Hasnayn Ahmed

    Easy to understand as usual… Thanks.. Waiting for next one.

  • Nice post @ravi8x:disqus… Got to know about Slim framework through this post.. πŸ™‚

  • Mike

    Ravi, just curious, are you using Eclipse or Android Studio for this?

  • Virender Dall

    Ravi sir not getting how to put value in header, pls help me

  • Udhayakumar

    Very nice article for beginners of REST. Thank you so much Ravi.

  • Ruslan Bekenev

    Thank you so much. It’s very good article.

  • Mat

    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

  • shashi

    Hii ravi i am geting
    error: true
    message: “Required field(s) name, email, password is missing or empty”

    please tell me how to solve this problem i am stcing from 2 days …where is fault i am not getting and its telling 404 bad request…

    • Marat Duisenov

      Because you need to fill not headers, but Payload values. First choice POST method for register not GET

  • D L

    The third part would be sweet!

  • AMI

    HI RAVI,


    • Kowal Kowalczyk

      use retrofit 2.1.

      • Jonathan

        Do you have it to work with retrofit 2 ? if yes can you share the source code? πŸ™‚

  • dskanth

    Very good explanation with diagrams and videos. Thanks a lot.

  • John

    How can we implement this tutorial on hosting?

  • sathu

    Thankyou so much ravi……. It’s nice article to learn REST API for the beginners….

  • vino

    The tutorial was excellent.It works fine for me in localhost but not on live server.On uploading the project to live server i got 404 not found exception..Anyone came across this issue..Pls help….

  • Delph69

    Hello there,
    I want to download the sources of the tutorial but when I sign up, I never get the email that would validate my account.
    How can I do?

    Thank you in advance

  • dimitris

    Excellent tutorial, Thank you very much!!

  • Pawan

    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

    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


      • 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?

          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


    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


  • Harsh Vardhan Srivastava

    Hi Ravi,

    Thanks for the tutorial, helped me a great deal.

    For those struggling with get_result error in php.

    * 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)


    if (!$result)

    throw new Exception(“Database Error [{$this->database->errno}] {$this->database->error}”);

    if ($result != NULL) {
    $response[“error”] = false;

    $response[“tasks”] = array();

    // looping through result and preparing tasks array
    foreach ($result as $task)
    $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);
    $response[“error”] = true;

    $response[“message”] = “The requested resource doesn’t exists”;
    echoRespnse(404, $response);


    public function getAllUserTasks($user_id) {
    $stmt = $this->conn->prepare(“SELECT t.id, t.task, t.status, t.created_at from tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?”);

    $stmt->bind_param(“i”, $user_id);
    $tasks = array();
    if ($stmt->execute())
    $stmt->bind_result($id, $task, $status, $created_at);

    $tmp = array();

    $tmp[“id”] = $id;
    $tmp[“task”] = $task;
    $tmp[“status”] = $status;

    $tmp[“created_at”] = $created_at;

    array_push($tasks, $tmp);
    return $tasks;

    • Reena Patel

      thanks a lot sir..you saved my day !!! πŸ™‚ πŸ™‚
      Really appreciable !!!

    • Arshit Aggarwal

      Thanks a lot man !!! It really helped me a lot…Thanks again… πŸ™‚

    • Arshit Aggarwal

      Thanks man!!! πŸ™‚ It helped me a lot

  • RajRB

    Hi Ravi,

    Thanks a lot for your work. It is helping me and a lot of people.

    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 ?

  • chirag

    public static class Webservice_ValidUser {
    //private static final String URL = “http://api.ogoing.com/user.asmx?op=ValidUser”;
    private static final String URL = urlmain+”user.asmx?op=ValidUser_New”;
    private static final String SOAP_ACTION_NEW = “http://www.ogoingapi.com/ValidUser_New”;
    * Getting Contact information
    * @param attendeeCredentials
    * @param inSeqNum
    * @return GetAttendeesContactInfoResponse
    public static JSONObject callWebServiceJson(String UserName, String Password, String DeviceId) {
    JSONObject jsonObj = null;

    String ValidLogin = “”
    + “”
    + “” + “”
    + “” + UserName + “” + “”
    + Password + “” + “” + portal
    + “” + “” + DeviceId + “”
    + “” + “” + “”;

    DefaultHttpClient httpClient = new DefaultHttpClient();
    String envoloper = String.format(ValidLogin);
    // request parameters
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 10000);
    HttpConnectionParams.setSoTimeout(params, 15000);
    // set parameter
    // POST the envelope
    HttpPost httppost = new HttpPost(URL);
    // add headers
    // Set Method Action
    httppost.setHeader(“soapaction”, SOAP_ACTION_NEW);
    httppost.setHeader(“Content-Type”, “text/xml; charset=utf-8”);
    String response = “”;
    try {
    // the entity holds the request
    HttpEntity entity = new StringEntity(envoloper);
    // Response Handler
    ResponseHandler responseHandler = new ResponseHandler() {
    public String handleResponse(HttpResponse response)
    throws ClientProtocolException, IOException {
    // get response entity
    HttpEntity entity = response.getEntity();
    // read the response as byte array
    StringBuffer out = new StringBuffer();
    byte[] b = EntityUtils.toByteArray(entity);
    // write the response byte array to a string buffer
    out.append(new String(b, 0, b.length));
    return out.toString();
    // Getting the response
    response = httpClient.execute(httppost, responseHandler);
    // Sending the Response to parsing class
    String stt[] = response.split(“”);
    String stt2[] = stt[1].split(“”);
    Log.i(“”, “stt” + stt);
    Log.i(“”, “stt2” + stt2);
    String my_string = stt2[0];

    Spanned abc = Html.fromHtml(Html.fromHtml(my_string).toString());
    String my_final_string = abc.toString();

    jsonObj = new JSONObject(my_final_string);
    String uname = jsonObj.getString(“UserName”);
    Log.i(“uname” + uname, “my_string” + my_string);
    } catch (Exception exc) {
    return jsonObj;

  • chirag



    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(“http://vmss.co.in/smarttransport/getdetail.php”);

    MultipartEntity data_to_send = new MultipartEntity(


    data_to_send.addPart(“journeyId”, new StringBody(journeyId));

    data_to_send.addPart(“delete”, new StringBody(“1”));


    HttpResponse response = httpclient.execute(httppost);

    HttpEntity entity = response.getEntity();

    is = entity.getContent();


    if(result != null)


    flag = true;


    }catch(Exception e)


    Log.e(“log_tag”, “Error in http connection”+e.toString());


    if(flag == true)





    BufferedReader reader = new BufferedReader(new InputStreamReader(is,”iso-8859-1”),8);


    sb = new StringBuilder();


    sb.append(reader.readLine() + “n”);

    String line=”0″;

    while ((line = reader.readLine()) != null)






    System.out.println(“else “+result);

    }catch(Exception e)




    return null;


  • Reena Patel

    Simply superb tutorial..keep it up man!!! you helped me manier times before…thank you so much πŸ™‚

  • Graves

    Many thanks.

  • Gatunox

    Hi, Ravi or Anyone.
    Does anyone knows where i can find a good tutorial on how to consume (use) this restfull api from my android application?

  • thanks a lot @ravi8x:disqus

  • Tiny

    Hai sir,
    Could you plse tell me where i get example api’s for doing jsonparsing.

  • Ravi, I’ve a doubt. Why 3 tables?.

    Can i add a new column to `tasks` named `user_id` which refers to the user’s id who made the task (FK). ?? Is that a bad approach ??

    • Andrew Nyago

      good Approach of course. Plus, maybe, user’s who like and dislike a task, and comments from other users. thanks for the tip.

  • Leoric

    great article, very helpful! thank you

  • Alois Napitalai

    Anyone got this working in LAMP?BTW very helpful tutorial

    • Andrew Nyago

      I am using it on Ubuntu 14.04

  • Giovanni Rizzotti

    Hi, great tutorial, thanks!

    Where is the one for the android implementation?

  • Ram Shrestha Shikarin

    how show the users from database in Advanced Rest Client

  • sweety

    please help need index.php for registration and login

  • vishakha singh

    How can I get solve my problem of api key is missing

  • subash khati

    Please help. I get this error while listing user’s tasks :-
    PHP Fatal error: Call to undefined method mysqli_stmt::get_result()

  • Seao

    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’, ‘*’);

  • lucky Rana

    Nice tutorial, Ravi

  • Rohit Shrivastava

    great explanation for freshers

  • Giovanni Rizzotti

    I really love this article. What do you think about an updated tutorial with the latest version of the SlimFramework?

    • Yeah, I’ll check. It’s a pain taking task updating the older articles as there are lot of articles in the queue. I am updating one by one.

      • Giovanni Rizzotti

        Cool! What do you think about update a tutorial like this with a fastest php framework like phalcon?

  • beeeku

    @ravi8x:disqus can you update or provide a skeleton like this with slim 3 !! It will be very helpful.

    • Yeah, I have noted down this, but lot of other articles are scheduled. It takes much time to update. Meanwhile please explore.

  • Ved Prakash

    404 error …. hw to solve this prblm??

  • PINKesh Darji

    Hello Ravi, Thanks for such a nice tutorial.
    I was getting ’email is not valid’ error then I comment it out email validation function now I am getting “error”: true,

    “message”: “Oops! An error occurred while registereing” — Kindly help me out.Thanks in advance

    • Dionisius Wahyu Adi Saputra

      enable .htaccess

  • Amita Kumari

    $app->run(); this function is not work. show 400 error.

  • article Designing a Secure REST (Web) API without OAuth by Riyad Kalla

    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!

    • Hi Riccardo

      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 πŸ™‚

  • Chandrakant

    Hello Ravi, I’m getting below error
    “error”: true,
    “message”: “Oops! An error occurred while registereing”

    please help me

  • vrushali

    Hi Ravi,

    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.

    • Hi Vrushali

      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??

    • Status field in users table is to enalbe / disable user if you want to restrict an user from login. In task table it defines task completion status. If it is 1, the task is completed.

  • Jacek Budzynski

    I’ve just started following this tutorial and tried to download the code but the button on top of the page doesn’t seem to work. Could someone provide me with the files from there please?

  • Ken Choong

    For whom who cant get the json result although the right parameter insert in the register endpoint.I face this problem beforre.I just have the solution. Follow this link http://stackoverflow.com/questions/41844896/slim-micro-framework-why-i-cant-insert-the-record-to-the-database/42025953#42025953 Hope this can help you.Happy coding

  • nikhil

    Warning: require(.././libs/Slim/Slim.php): failed to open stream: No such file or directory in C:xampphtdocstask_managerv1index.php on line 5

    how to solve this warning. i am unable to execute

    • Ken Choong

      you need to paste the Slim library inside libs folder.look at part 2

  • Mahi

    i got 500 internal error while checking first api link to register..??

  • Sandeep

    Hello, How we can upload image using slim framework? Please give any example.

    • Hedi Chkir


      I’m also looking for that.

      Could your please email me at incbulldozer@gmail.com if you have an example.

      thank you

  • Bunna Ch

    Hi Ravy,
    Can you please explain more about API Key?
    why you use API Key in creating, reading, updating and deleting task?
    and in Registration and Login you don’t use it.
    Thanks in advanced.

    • Yes, API key is used to perform all the operations after login. So you won’t get the API key until unless you register / login. And the key will be unique to every user.

      • Bunna Ch

        Ravi, but what do you mean by “secure your API using an API key”? secure from accessing database or accessing API?
        I am new to that API key technique. so could you please explain more?

        • Please Google it. It can’t be explained in one line

  • Siddarth G

    hi , the link to next tutorial is not working

  • Emmanuel Okezie Ogbonna

    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

    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?

    • Hemant

      Same here… Any Help ?

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

  • nafees ahmed

    you are my hero πŸ™‚

  • Guilherme

    Perhaps the best tutorial on the Internet, but its update to Slim 3 is not easy to do =/ … It’d be great if there could be a new version of this

    • Yup.. I need to update this.

      • Guilherme

        Nevertheless, this is the best tutorial blog on Android I ever found… Big fan (and very thankful)!

      • Devyani Kotadiya

        please ravi update your authenticate function in index.php file of v1 folder….just update Authorization with authorization

        function authenticate(SlimRoute $route) {
        // Getting request headers
        $headers = apache_request_headers();
        $response = array();
        $app = SlimSlim::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);

        } else {
        global $user_id;
        // get user primary key id
        $user_id = $db->getUserId($api_key);
        } else {
        // api key is missing in header
        $response[“error”] = true;
        $response[“message”] = “Api key is misssing”;
        echoRespnse(400, $response);

        • Thanks, Devyani. It completely depends on the server configuration.

          • Devyani Kotadiya


  • yazi

    why cannot add authorization header in new advance rest client

    • Devyani Kotadiya

      please update Authorization with authorization in index.php of v1 folder…then you can add authorization header

  • yazi

    it says Api key is misssing

  • Gerardo Herrera

    This tutorial is Excellent , Thank you. πŸ™‚

  • Amal Shiwantha

    Thank you, a Nice tutorial.

  • Galih Prasetio

    Arigatogozaemas Ravi Tamada San

  • Jubayar Hosan

    why you write all api in index.php file. In Slim all Resi api have to write in a single file (index.php) ?

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

    Could anyone suggest me in how to fix that problem?
    Thank you

    • Check your server error logs. It might be something to do with php / apache / nginx configurations.

      • IT ιƒ¨ι–€ηœ‹θ­·ιŠ€θ‘Œ

        Thank you, Ravi, for the response.

        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.

        Thank you for the awesome tutorial.

  • abhi

    Hi how to connect other website, which is not owned by me

  • IT ιƒ¨ι–€ηœ‹θ­·ιŠ€θ‘Œ

    Hello, Ravi.
    Do you have any recommendation on how to forbid access to folder contents by public but still can be accessed by the files inside it?

    I used Option -indexes in my .htaccess, but it does forbid the whole function.
    Thank you in advance.

  • PaweΕ‚ SzymaΕ„ski

    For now in Slim library files file Slim.php is not exist how to use library in current version?

    • KneK Man

      version 2.3.5 old version not compatible with 3.9

  • 김민석

    What is the Slim framework version?

    • KneK Man

      version 2.3.5

  • Chaudary Usman

    Thanks Ravi Tamada for making such a Great REST API Tutorial πŸ™‚
    It’s a request, Please update it to work with Slim 3. It will be of much help for Everyone and Appreciated.

  • Silvio Bonilha

    Hi, very good your presentation…. can i you help me… IΒ΄m trying to use slimp, but IΒ΄m using the version 3… what I need to your tutorial works fine?…

  • Kuldeep Kumar

    please help
    “s”: 1,
    “m”: {
    “m_u_id”: “370”,
    “m_u_user_id”: “4716”,
    “m_u_message_type”: “Notification”,
    “m_u_message”: “title!!!!!!1^^^text!!!!!!Your message is posted successfully to ADMIN, Please note your reference number for further communication. We will update you on your concern as soon as possible.^^^id!!!!!!110^^^extra!!!!!!NAME=Lungani P Magwaza######TICKET NO=EK”,
    “m_u_a_date”: “31-Oct-2018 14:08:14”,
    “m_u_type”: “Learner”,
    “m_u_expiry_date”: “”

    “m_u_message”: “title!!!!!!1^^^text!!!!!!Your message is posted
    successfully to ADMIN, Please note your reference number for further
    communication. We will update you on your concern as soon as
    possible.^^^id!!!!!!110^^^extra!!!!!!NAME=Lungani P Magwaza######TICKET

    how to set in lbldata i have used

    JSONObject dataM = outputJson.getJSONObject(KEY_DATA);
    String notificationId=dataM.getString(“m_u_id”);
    int notificationIdInt=Integer.parseInt(notificationId);
    if(notificationIdInt>0) {

    printLogs(LogTag,”notificationIdInt”,”WE IN”);

    String m_u_message=”null”;
    Spanned Message;
    String mItem=null;
    if(m_u_message!=null) {

    printLogs(LogTag,”notificationIdInt”,”TESTING m_u_message MESSAGE”);

    String DateString = dataM.getString(“m_u_message”);



    // String[] arrOfStr = DateString.split(“[!!!!!! ^^^]+”);

    // String[] arrOfStr = DateString.split(“[! ^ # = ,]+”);
    String[] arrOfStr = DateString.split(“[!!!!!! ^^^ ######]+”);

    for (String a : arrOfStr) {
    printLogs(LogTag,”notificationIdInt”,”TESTING FOR MESSAGE”+a);
    lblData.setText(a); //here only single text recieve not all text
    // lblData.setText(arrOfStr[0] + ” ” + arrOfStr[1] + ” ” + arrOfStr[2] + ” ” + arrOfStr[3] );