March 11, 2014 6:36 pm

Simple PHP REST API with Slim, PHP & MySQL

I have received many requests from readers and after lots of searching I found out a light weight frame work to create PHP RESTful API Tutorial. There are a number of frame works available and the one I chose is SLIM (it is a micro framework that helps you efficiently write powerful web services). This tutorial gives you complete examples of creating full Restful API using multiple HTTP methods like GET, POSTPUT and DELETE. You would get the output in JSON and create a user data for all options, download code available.

How to create RESTful API / Web Service with Slim, PHP & 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:
  • 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.

    • Huzoor, may be the error is the php version, because Slim require v5.5+

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

        • Samiul Haque

          dont use windows

  • 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

  • upendra

    hey how to use update and delete function. I am getting the user by name and id but i don’t know how to update or delete user by using this api.Thanks in advance

  • Samir Sudrik

    i did the payment, but didnt get any download option for the code.

    • huzoorbux

      Script emailed please check.

  • I bought it but I never received the download link 🙁

    • huzoorbux

      Facing some issues for auto script download we are working on it to fix it.
      Code emailed to you.

      • Thanks, I received it and got it working 🙂 On index.php where would I put header(‘Content-Type: application/json’); so it’s serving as a proper json file?

        • huzoorbux

          header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

          • Tried the below but doesn’t seem to be displaying the header as json

            header(‘Content-Type: application/json’);


            require ‘Slim/Slim.php’;

          • huzoorbux

            What is the issue you are facing?

          • no error just header isn’t showing as json

          • huzoorbux

            Can you share website link in email.

          • no error just header isn’t showing as json


    I’m starting to get to grips with this web service now and I have integrated it in to some of my projects. Fab work! I just wondered is there an example of using the ‘PUT’ without the form? like just hitting a webpage and it updates a database?

  • Ken Mau

    I purchased it as well but didn’t get the files or anything on my email 🙁

  • Chema Gracia

    I bought it but I never received the download link 🙁

    • @chemagracia:disqus Download link emailed you.

    • @chemagracia:disqus Download link emailed you.

  • Chema Gracia

    I put the code in a hosting and I get 404 page not found. I think .htaccess is right and also the conn params. What do you think?

  • Michel

    Hi there, I purchased the code, and the download link from the email is not working. Could you please email me the code?

  • 김민석

    After completion of payment e-mail link is not working.

  • Isaak Ordoñez

    Hi, I purchased the code, and the download link from the email is not working. Could you please email me the code?

  • Jonathan Parel

    Hi, I paid via paypal (payment #1979) but I have not received anything. Could you please email me the code, too?

    • Code Emailed please check.

      • Beto

        hello, I had the same problem made the payment and have not received the script, the payment number in paypal: 4620.

  • Jonathan Parel

    Thanks, I got it.

  • Jonathan Parel

    Hi. I started running your examples, copying the “Slim folder and its contents, .htaccess, form.php, index.php” into my “C:XAMPPHTDOCSrestapi”. I also created a “phpgang database” and executed the “restAPI.sql” in Navicat to create the table “restapi”. Now here are the results: #1 – I am getting a “404 Page Not Found” when I run “localhost/restapi/index.php; #2 – “localhost/restapi/form.php” shows up the form but nothing happens. When I click the ADD button after filling up the form, I get an “Object not found! Error 404.” My IDE is Netbeans 8.0.2. Please help me make this work I need to learn this for my next project. Thanks.

  • Hello,,, can Help me,,,
    How upload file (image, video, etc) into Database MYSQL using SLIM web services?

  • Hello,,, can Help me,,,
    How upload file (image, video, etc) into Database MYSQL using SLIM web services?

  • Rohit Shrivastava
  • Gagan

    Can you give me one good reason why one shall purchase this because same is available for free on many sites such as

    • You can download it from that website for free.

      “If you are good at something never do it for free”

  • TheRigz

    Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.

  • TheRigz

    Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.

  • TheRigz

    Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.

  • TheRigz

    Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.

  • Netscope Systems

    I just did a payment and haven’t received anything. Payment ID:2942

  • Adrianux Velden

    Hi Huzoor.

    I have already paid for the code but only see the paypal charge and not the download link. Please helpme!


  • Wim Porters

    Hi, I paid but didn’t receive a download link. Could you please send it?

  • Otacilio Alves

    Hi, I paid via paypal (payment #3148) but I have not received anything. Could you please email me the code, too? The link I received in my email is not working also.

    • Marcelo Luz

      Oi! Ele respondeu, Otacilio? Se sim, o que ele fornece por este valor? Obrigado!

  • Jamie

    I purchased this product but didnt get any email to download the code..

    (Payment: 3263)

    Please send me download link!

  • Humphrey Pietersen

    Really useful script

  • Walid Msilini

    thank you it is really good