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.
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
- getUsers
- getUser
- findByName
- addUser
- updateUser
- 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 } ?>
[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.
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!
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.
its working great..
if function is in different file then how we call it on the basis of url.
Include that function file on that page and call the function
Hats off!!! Brilliant Tutorial Guys
i can’t download this code 🙁 although i already subscribed.please help me
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.
What email you have used to subscribe? list updated just 2 minutes ago.
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.
so how to download this code?? it doesnt work, i cant download…please
me too, I can’t download this excellent tuto! please help
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
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.
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?
Create CI custom module to use these methods.
I subscribed but I can’t download code
It wont let me download either, and subscribed for over 12 hours now. Anybody who has already downloaded it put it online somewhere please?
u r ass
I could not download the code. Not really fun.
Hello,
Could someone please help to download the code. Subscribed two days ago.
What do you suggest for token based authentication?
Getting “Internal Server Error” even if my database config setting is correct.
Turn on errors and try again
wts wrng wd downloading code , use github or something more convenient :/
if someone has code , can you kindly share it with me , i am having issues with downloading
very nice
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
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.
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
Simply Superb !!!! Thank you so much !!! You saved my day 🙂 🙂
PlEASE HELP ME TO KNOW HOW TO CALL THE API.
AM CALLING LIKE… http://localhost/api/users I GOT ERROR
What error you are getting?
Not Found
The requested URL /api/users was not found on this server.
i have one problem above code run on localhost but not run in live….?
Try to debug it must be some error in code.
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+
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
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
Try to run it on some host it will give you errors on localhost.
i am tried with host but it shows same error , please give solution,
dont use windows
hi thats gr8 tutorial easy to understand thanks so much but i want to know how to upload file or image using rest api
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
i did the payment, but didnt get any download option for the code.
Script emailed please check.
I bought it but I never received the download link 🙁
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?
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’);
ini_set(“display_errors”,1);
require ‘Slim/Slim.php’;
What is the issue you are facing?
no error just header isn’t showing as json
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?
Hello @disqus_pMtjuNzaZT:disqus Please read this it will help you. http://stackoverflow.com/questions/8054165/using-put-method-in-html-form
I purchased it as well but didn’t get the files or anything on my email 🙁
I bought it but I never received the download link 🙁
@chemagracia:disqus Download link emailed you.
@chemagracia:disqus Download link emailed you.
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?
Can you please share your link.
Hi there, I purchased the code, and the download link from the email is not working. Could you please email me the code?
Send you code in email please check.
After completion of payment e-mail link is not working. [email protected]
Hi, I purchased the code, and the download link from the email is not working. Could you please email me the code?
Code Emailed please check.
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.
hello, I had the same problem made the payment and have not received the script, the payment number in paypal: 4620.
Thanks, I got it.
Hi Jonathan, I’m having the same issues as yours before. Did you solve them? When I type in localhost/restapi/ then i will receive 404 Page not found, can you help me if you know the solution? thanks!!
You must configure mod_rewrite for .htaccess http://stackoverflow.com/questions/14490209/use-htaccess-file-on-an-apache-localhost-server
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.
you face .htaccess issues on windows host try to move it to some Linux hosted account. For free hosting try this: http://www.000webhost.com/
Hi, I want to buy “RESTful API / Web Service with Slim, PHP & MySQL” What do I get? all the code? do I need to fix anything to get it to work?
Attach
Buy it form https://www.phpgang.com/how-to-create-restful-api-webservice-with-slim-php-and-mysql_588.html
Buy it form https://www.phpgang.com/how-to-create-restful-api-webservice-with-slim-php-and-mysql_588.html
Buy it form https://www.phpgang.com/how-to-create-restful-api-webservice-with-slim-php-and-mysql_588.html
Hello,,, can Help me,,,
How upload file (image, video, etc) into Database MYSQL using SLIM web services?
Thank.
Hello,,, can Help me,,,
How upload file (image, video, etc) into Database MYSQL using SLIM web services?
Thank.
GET http://localhost/event_booking/api/users 404 (Not Found)
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
You can download it from that website for free.
“If you are good at something never do it for free”
Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.
Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.
Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.
code emailed
Yea I also just did a PayPal payment, but I have not received anything… Pmt #2891. The link just takes me to your homepage.
I just did a payment and haven’t received anything. Payment ID:2942
Hi Huzoor.
I have already paid for the code but only see the paypal charge and not the download link. Please helpme!
Thanks.
Hi, I paid but didn’t receive a download link. Could you please send it?
Thanks!
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.
Oi! Ele respondeu, Otacilio? Se sim, o que ele fornece por este valor? Obrigado!
I purchased this product but didnt get any email to download the code..
(Payment: 3263)
Please send me download link!
Really useful script
thank you it is really good
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
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
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
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
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 ?
Never mind, I’ve found it in the spam box.
HI, just paid for the download but haven’t received anything yet???
Check your spam folder.
Just send you code
Nice way to create a Restful api, Good Work.
i’m confused which all files i need to make!
can i knw how a image can be uploaded in slim webservice with get or put method
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}
Hello i paid but i dont have any link could you send me ?