March 11, 2014 6:36 pm

How to create RESTful API / Web Service with Slim, PHP and MySQL

Receive many requests from readers and after lots of searching found a lightweight framework create RESTful API in PHP. There are number of frameworks available the one I chose is Slim ( is a PHP micro framework that helps you quickly write powerful web services). This tutorial gives you complete examples of creating complete Restful API using multiple HTTP methods like GET, POST, PUT and DELETE. It return you output in JSON and create a User data for all options, download code available for free.

How to create RESTful API / Webservice with Slim, PHP and MySQL

HTTP methods:

GET: Used to retrieve and search data.

POST: Used to insert data.

PUT: Used to update data.

DELETE: Used to delete data.

Add below .htaccess file in your api folder http://localhost/api

Database design and table:
database name => phpgang
table name => restAPI
column names => id, name, email, ip, date
Database file run in your MySQL to create database and add data in table.

Database configuration

Edit database name, user and password as per your configuration

Used PDO connection you can use as per your ease and I have added this function in same methods file you can also manage them as per your projects.

Implement API

We have created 6 API methods

  1. getUsers
  2. getUser
  3. findByName
  4. addUser
  5. updateUser
  6. deleteUser

Define HTTP routes:

These all routes call individual function as defined above and in the last $app->run(); used to run Slim application.

let’s see functions:

1. getUsers: $app->get(‘/users’, ‘getUsers’);

This function simply return all users information as you can see in this query, to call this API use this URL http://localhost/api/users this is it for your first API using get route.

2. getUser: $app->get(‘/users/:id’,    ‘getUser’); In this route we are sending id.

This function check record of given id and return if found any thing,  to call this API use this URL http://localhost/api/users/1.

3. findByName: $app->get(‘/users/search/:query’, ‘findByName’); Route is used to search record with extra parameter and a search query with simple get method.

This function search in database for your given query, to call this API use this URL http://localhost/api/users/search/phpgang.

4. addUser: $app->post(‘/users’, ‘addUser’); API used to add new record and accept post.

This API accept post request and insert submitted data in your database as we received parameters in starting of that function. To call this API I have used cURL, you can use jQuery or any other technique.

This form will be submitted to your action file and there is a curl and that curl will post data as I have used a hidden input of _METHOD with POST value this is because some times your cURL don’t Post data to API (faced this so used this for post as well) and Slim give us this functionality to method override and as our modern browsers do not have native support to PUT and delete so we have to use method overriding like below.

cURL function to post data:

5. updateUser: $app->put(‘/users/:id’, ‘updateUser’); This route accept put HTTP method.

This API function update your data by id, to call this API we need to again use cURL and HTML form.

6. deleteUser: $app->delete(‘/users/:id’,    ‘deleteUser’); Route used to delete specific ID.

This API function accept HTTP delete request and to send HTTP delete method we have to used method overriding using our hidden field named _METHOD and value will be DELETE form and cURL code given below.

Read more: Create a web service with PHP

That’s all for our one of the biggest tutorial for RESTful API, I hope you like this tutorial and please don’t forget to give us your feedback and any issue you have faced in this tutorial please do comment we try our level best to solve your problems.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.

Tutorial Categories:
  • s.shivasurya

    awsome! i was working recently with simple REST API ! you have provided slim also ! thanks author!
    and uses of this REST API ,we could create simple html5 apps using phonegap + json will be used to return data using jquery ajax!

  • Umair Ahmed

    Thanks hb bhai, its really awesome tutorial, now a days I am working on creating an apis, thanks man, your all tutorials are very simple and easy to understand.

  • Love Singhal

    its working great..
    if function is in different file then how we call it on the basis of url.

    • huzoorbux

      Include that function file on that page and call the function

  • Mudassar Muhammad Khan

    Hats off!!! Brilliant Tutorial Guys

  • tiny angel

    i can’t download this code :( although i already subscribed.please help me

    • chandu

      you have wait 6 hours after subsciption because it will take 6 hours to update ur subscription .i think now u can download because u subscribed 24 hours ago right.

      • huzoorbux

        What email you have used to subscribe? list updated just 2 minutes ago.

    • chandu

      you have to wait 6 hours after subscription . it will take effect after 6 hours and it mentioned below the subscription please read clearly ok . i think u can download now it has completed 24 hours.

  • Nismol

    so how to download this code?? it doesnt work, i cant download…please

  • cloudman

    me too, I can’t download this excellent tuto! please help

  • chandu

    hi friends , i have a small problem with this code . It is runing but it not calling any function and it is showing blank page when i a m submitting the form, Please any one can help me

  • hard

    i cant run the url

    when i enter this address, http://localhost/api/users

    it will returns me to the xampp homepage

    help me, thanks.

  • Onur Gültekin

    I could not run the code. I am using codeigniter on my web site and I created a subdirectory named “api” and deployed your codes to api folder but it returns 404 all the time.
    Do you have any idea to help me?

    • huzoorbux

      Create CI custom module to use these methods.

  • Kemosaif

    I subscribed but I can’t download code

  • Ash

    It wont let me download either, and subscribed for over 12 hours now. Anybody who has already downloaded it put it online somewhere please?

    • baba

      u r ass

  • Huong

    I could not download the code. Not really fun.

  • David

    Could someone please help to download the code. Subscribed two days ago.

  • tim

    What do you suggest for token based authentication?

  • Shirish K.

    Getting “Internal Server Error” even if my database config setting is correct.

    • huzoorbux

      Turn on errors and try again

  • batman

    wts wrng wd downloading code , use github or something more convenient :/

  • batman

    if someone has code , can you kindly share it with me , i am having issues with downloading

  • Shaikh Mohd Faizan

    very nice

  • arc

    hey, that very nice, its really works for me, thanks.
    But i have another issues,

    1. can you give me example api that requests user data as I need, ex: i request data user but i just need ‘name’ field, so i dont need the other fields.

    2. how if the other field that i need is in different tables, ex: i request field ‘name’ that exist in table user and field ‘user_level’ in table ‘user_privilage’, these two tables have field ‘user_level_id’ as foreign key

    sory for my bad english

  • Jay

    while I run the url http://localhost/restapi/ it redirect me to xampp screen , why this happened any solution. I am using ubuntu 12.04 xampp.

    • sahil

      RewriteEngine On

      RewriteCond $1 !^(index.php|resources|robots.txt)

      RewriteCond %{REQUEST_FILENAME} !-d

      RewriteCond %{REQUEST_FILENAME} !-f

      RewriteRule ^(.*)$ index.php [QSA,L]

      Use the above code in .htaccess, it would work

  • Харон

    I don’t see DI here, although Slim does have it

  • Харон

    I don’t see DI here, although Slim does have it

  • Reena

    Simply Superb !!!! Thank you so much !!! You saved my day :) :)



    AM CALLING LIKE… http://localhost/api/users I GOT ERROR

    • huzoorbux

      What error you are getting?

      • chandika

        Not Found
        The requested URL /api/users was not found on this server.

  • pravin

    i have one problem above code run on localhost but not run in live….?

    • huzoorbux

      Try to debug it must be some error in code.

  • huzoorbux

    Turn on errors must be some error in code or database connection.

  • mickael

    nice tutorial thanks :D,did you have please an other tutorial concerning the creation of a rest API with symfony2 and angularJS as a client thanks for help

  • Balu Arutla

    please help mee!

    I am trying to call the URL is http://localhost/api/getUsers , But it showing the error is “The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.” i didn’t
    please help

    • huzoorbux

      Try to run it on some host it will give you errors on localhost.

      • Balu Arutla

        i am tried with host but it shows same error , please give solution,

  • sam

    hi thats gr8 tutorial easy to understand thanks so much but i want to know how to upload file or image using rest api