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, POST,�PUT 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

Download the full code package
[purchase_link id=”1131″ style=”button” color=”blue” text=”Purchase” direct=”true”]

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

RewriteEngine On

RewriteBase /api # if hosting api files on root use only /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

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

-- 
-- Table structure for table `restAPI`
-- 

CREATE TABLE `restAPI` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(240) NOT NULL,
  `email` varchar(240) NOT NULL,
  `password` varchar(240) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

Database configuration

Edit database name, user and password as per your configuration

function getConnection() {
    try {
        $db_username = "DATABASE_NAME";
        $db_password = "********";
        $conn = new PDO('mysql:host=localhost;dbname=root', $db_username, $db_password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    return $conn;
}

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:

$app->get('/users', 'getUsers'); // Using Get HTTP Method and process getUsers function
$app->get('/users/:id',    'getUser'); // Using Get HTTP Method and process getUser function
$app->get('/users/search/:query', 'findByName'); // Using Get HTTP Method and process findByName function
$app->post('/users', 'addUser'); // Using Post HTTP Method and process addUser function
$app->put('/users/:id', 'updateUser'); // Using Put HTTP Method and process updateUser function
$app->delete('/users/:id',    'deleteUser'); // Using Delete HTTP Method and process deleteUser function
$app->run();

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’);

function getUsers() {
    $sql_query = "select `name`,`email`,`date`,`ip` FROM restAPI ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt   = $dbCon->query($sql_query);
        $users  = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"users": ' . json_encode($users) . '}';
    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }    
}

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.

function getUser($id) {
    $sql = "SELECT `name`,`email`,`date`,`ip` FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $user = $stmt->fetchObject();  
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

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.

function findByName($query) {
    $sql = "SELECT * FROM restAPI WHERE UPPER(name) LIKE :query ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);
        $query = "%".$query."%";
        $stmt->bindParam("query", $query);
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"user": ' . json_encode($users) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

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

create PHP REST API

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

function addUser() {
    global $app;
    $req = $app->request(); // Getting parameter with names
    $paramName = $req->params('name'); // Getting parameter with names
    $paramEmail = $req->params('email'); // Getting parameter with names

    $sql = "INSERT INTO restAPI (`name`,`email`,`ip`) VALUES (:name, :email, :ip)";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("ip", $_SERVER['REMOTE_ADDR']);
        $stmt->execute();
        $user->id = $dbCon->lastInsertId();
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

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.

<?php
if($_POST){
    echo post_to_url("http://localhost/users", $_POST);
} else{
 ?>
ADD RECORD.
<form action="" method="post">
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="POST" />
<input type="submit" value="A D D" />
</form>
<?php 
}
?>

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.

PHP RESTful API

<input type="hidden" name="_METHOD" value="POST" /> <!-- POST data -->
<input type="hidden" name="_METHOD" value="PUT" /> <!-- PUT data -->
<input type="hidden" name="_METHOD" value="DELETE" /> <!-- DELETE data -->

cURL function to post data:

function post_curl($_url, $_data) {
   $mfields = '';
   foreach($_data as $key => $val) { 
      $mfields .= $key . '=' . $val . '&'; 
   }
   rtrim($mfields, '&');
   $pst = curl_init();

   curl_setopt($pst, CURLOPT_URL, $_url);
   curl_setopt($pst, CURLOPT_POST, count($_data));
   curl_setopt($pst, CURLOPT_POSTFIELDS, $mfields);
   curl_setopt($pst, CURLOPT_RETURNTRANSFER, 1);

   $res = curl_exec($pst);

   curl_close($pst);
   return $res;
}

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

function updateUser($id) {
    global $app;
    $req = $app->request();
    $paramName = $req->params('name');
    $paramEmail = $req->params('email');

    $sql = "UPDATE restAPI SET name=:name, email=:email WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("id", $id);
        $status = $stmt->execute();

        $dbCon = null;
        echo json_encode($status); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

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

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST); // add id after last slash which you want to edit.
} else{
UPDATE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to update" /><br>
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="PUT" />
<input type="submit" value="U P D A T E" />
</form>
<?php 
}
?>

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

function deleteUser($id) {
    $sql = "DELETE FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $status = $stmt->execute();
        $dbCon = null;
        echo json_encode($status);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

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.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST);
} else{
 ?>
DELETE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to delete" /><br>
<input type="hidden" name="_METHOD" value="DELETE" />
<input type="submit" value="D E L E T E" />
</form>
 <?php 
}
?>
Download the full code package

[purchase_link id=”1131″ style=”button” color=”blue” text=”Purchase” direct=”true”]

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:

114 responses to “Simple PHP REST API with Slim, PHP & MySQL”

  1. 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!

  2. Umair Ahmed says:

    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.

  3. Love Singhal says:

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

  4. Mudassar Muhammad Khan says:

    Hats off!!! Brilliant Tutorial Guys

  5. tiny angel says:

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

    • chandu says:

      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.

    • chandu says:

      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.

  6. Nismol says:

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

  7. cloudman says:

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

  8. chandu says:

    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

  9. hard says:

    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.

  10. Onur Gültekin says:

    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?

  11. Kemosaif says:

    I subscribed but I can’t download code

  12. Ash says:

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

  13. Huong says:

    I could not download the code. Not really fun.

  14. David says:

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

  15. tim says:

    What do you suggest for token based authentication?

  16. Shirish K. says:

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

  17. batman says:

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

  18. batman says:

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

  19. Shaikh Mohd Faizan says:

    very nice

  20. arc says:

    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
    Thanks

  21. Jay says:

    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 says:

      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

  22. Харон says:

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

  23. Харон says:

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

  24. Reena says:

    Simply Superb !!!! Thank you so much !!! You saved my day 🙂 🙂

  25. SREERAJ says:

    PlEASE HELP ME TO KNOW HOW TO CALL THE API.

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

  26. pravin says:

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

  27. huzoorbux says:

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

  28. mickael says:

    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

  29. Balu Arutla says:

    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

  30. sam says:

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

  31. upendra says:

    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

  32. Samir Sudrik says:

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

  33. I bought it but I never received the download link 🙁

  34. Liverpool.li says:

    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?

  35. Ken Mau says:

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

  36. Chema Gracia says:

    I bought it but I never received the download link 🙁

  37. Chema Gracia says:

    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?

  38. Michel says:

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

  39. 김민석 says:

    After completion of payment e-mail link is not working. [email protected]

  40. Isaak Ordoñez says:

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

  41. Jonathan Parel says:

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

  42. Jonathan Parel says:

    Thanks, I got it.

  43. Jonathan Parel says:

    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.

  44. Awan says:

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

  45. Awan says:

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

  46. Gagan says:

    Can you give me one good reason why one shall purchase this because same is available for free on many sites such as http://www.9lessons.info/2014/12/create-restful-services-using-slim-php.html

  47. TheRigz says:

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

  48. TheRigz says:

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

  49. TheRigz says:

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

  50. TheRigz says:

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

  51. Netscope Systems says:

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

  52. Adrianux Velden says:

    Hi Huzoor.

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

    Thanks.

  53. Wim Porters says:

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

  54. Otacilio Alves says:

    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.

  55. Jamie says:

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

    (Payment: 3263)

    Please send me download link!

  56. Humphrey Pietersen says:

    Really useful script

  57. Walid Msilini says:

    thank you it is really good

  58. Annoyed by your newsletters says:

    why did i get this almost 3 years old article today in the newsletter? i think its time to unsuscribe, i wont be able to download any source code, but seeing how you charge money for that… i dont give a damn. Bye

  59. Annoyed by your newsletters says:

    why did i get this almost 3 years old article today in the newsletter? i think its time to unsuscribe, i wont be able to download any source code, but seeing how you charge money for that… i dont give a damn. Bye

  60. Annoyed by your newsletters says:

    why did i get this almost 3 years old article today in the newsletter? i think its time to unsuscribe, i wont be able to download any source code, but seeing how you charge money for that… i dont give a damn. Bye

  61. Annoyed by your newsletters says:

    why did i get this almost 3 years old article today in the newsletter? i think its time to unsuscribe, i wont be able to download any source code, but seeing how you charge money for that… i dont give a damn. Bye

  62. kasaiconnect says:

    Hi i’ve made a payment with the following email [email protected] address and I haven’t gotten the source code yet. Can you check it out ?

  63. Midge Stanger says:

    HI, just paid for the download but haven’t received anything yet???

  64. Nice way to create a Restful api, Good Work.

  65. Firdous Farooq Bhat says:

    i’m confused which all files i need to make!

  66. deepak shah says:

    can i knw how a image can be uploaded in slim webservice with get or put method

  67. David MacDougall says:

    I looks like 3 years of comments all talking about the same thing. No code download and then problems executing the code. I’ve got past the first obstacle, setup the code running on osx under MAMP and tried all the solutions already posted concerning socks, .htaccess contents and configuration files.

    I am getting a Slim Application Error as shown below.
    I have the database setup and I’ve tested it in MySQLWorkbench.
    The error is on line return $conn; which is not being set at line
    $conn = new PDO(‘mysql:host=localhost;dbname=api_db’, ‘root’, ‘root’);
    but I am now lost.

    What do I need to do to get this working?

    ERROR MESSAGE

    ERROR: SQLSTATE[HY000] [2002] No such file or directory
    Slim Application Error
    The application could not run because of the following error:
    Details
    Type: ErrorException
    Code: 8
    Message: Undefined variable: conn
    File: /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/index.php
    Line: 150
    Trace
    #0 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/index.php(150): SlimSlim::handleErrors(8, ‘Undefined varia…’, ‘/Users/dave/Doc…’, 150, Array)

    #1 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/index.php(28): getConnection()
    #2 [internal function]: getUsers()
    #3 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/Slim/Route.php(454): call_user_func_array(‘getUsers’, Array)
    #4 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/Slim/Slim.php(1316): SlimRoute->dispatch()
    #5 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/Slim/Middleware/Flash.php(85): SlimSlim->call()
    #6 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/Slim/Middleware/MethodOverride.php(92): SlimMiddlewareFlash->call()
    #7 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/Slim/Middleware/PrettyExceptions.php(67): SlimMiddlewareMethodOverride->call()
    #8 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/Slim/Slim.php(1263): SlimMiddlewarePrettyExceptions->call()
    #9 /Users/dave/Documents/Projects/Websites/HelpMe.Chat/www/api/index.php(21): SlimSlim->run()
    #10 {main}

  68. Stephane says:

    Hello i paid but i dont have any link could you send me ?

Leave a Reply

Your email address will not be published. Required fields are marked *