Create and Consume Simple REST API in PHP
In this tutorial, we will create and consume simple REST API in PHP. REST enables you to access and work with web based services. But before moving ahead let me explain what is REST and how does it work.
Note: This tutorial is just for REST API conceptual purpose, to implement it on live environment you will need to ensure security measure to mitigate SQL injection and other security issues.
Additionally, you can use PHP PDO prepared statements to avoid SQL injection.
What is REST?
REST stands for Representational State Transfer, REST is an architectural style which defines a set of constraints for developing and consuming web services through standard protocol (HTTP). REST API is a simple, easy to implement and stateless web service. There is another web service available which is SOAP which stands for Simple Object Access Protocol which is created by Microsoft.
REST API is widely used in web and mobile applications as compared to SOAP. REST can provide output data in multiple formats such as JavaScript Object Notation (JSON), Extensible Markup Language (XML), Command Separated Value (CSV) and many others while SOAP described output in Web Services Description Language (WSDL).
Readers Also Read: Laravel 10 User Roles and Permissions
How Does REST API Work
REST requests are related to CRUD operations (Create, Read, Update, Delete) in database, REST uses GET, POST, PUT and DELETE requests. Let me compare them with CRUD.
- GET is used to retrieve information which is similar to Read
- POST is used to create new record which is similar to Create
- PUT is used to update record which is similar to Update
- DELETE is used to delete record which is similar to Delete
Readers Also Read: Laravel 10 REST API using Sanctum Authentication
Readers Also Read: Laravel 10 REST API using Passport Authentication
How to Create and Consume Simple REST API in PHP
JSON format is the most common output format of REST API, we will use the JSON format to consume our simple REST API. We will developed an online transaction payment REST API for our example. I will try to keep it as simple as possible so i will use GET request to retrieve information.
- Create REST API in PHP
- Consume REST API in PHP
1. Create REST API in PHP
To create a REST API, follow these steps:
- Create a Database and Table with Dummy Data
- Create a Database Connection
- Create a REST API File
1. Create a Database and Table with Dummy Data
To create database run the following query.
CREATE DATABASE allphptricks;
To create a table run the following query. Note: I have already attached the SQL file of this table with dummy data, just download the complete zip file of this tutorial.
CREATE TABLE IF NOT EXISTS `transactions` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`order_id` int(50) NOT NULL,
`amount` decimal(9,2) NOT NULL,
`response_code` int(10) NOT NULL,
`response_desc` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;
2. Create a Database Connection
Just create a db.php file and paste the following database connection in it. Make sure that you update these credentials with your database credentials.
// Enter your Host, username, password, database below.
$con = mysqli_connect("localhost","root","","allphptricks");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
3. Create a REST API File
Create a api.php file and paste the following script in it.
<?php
header("Content-Type:application/json");
if (isset($_GET['order_id']) && $_GET['order_id']!="") {
include('db.php');
$order_id = $_GET['order_id'];
$result = mysqli_query(
$con,
"SELECT * FROM `transactions` WHERE order_id=$order_id");
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_array($result);
$amount = $row['amount'];
$response_code = $row['response_code'];
$response_desc = $row['response_desc'];
response($order_id, $amount, $response_code,$response_desc);
mysqli_close($con);
}else{
response(NULL, NULL, 200,"No Record Found");
}
}else{
response(NULL, NULL, 400,"Invalid Request");
}
function response($order_id,$amount,$response_code,$response_desc){
$response['order_id'] = $order_id;
$response['amount'] = $amount;
$response['response_code'] = $response_code;
$response['response_desc'] = $response_desc;
$json_response = json_encode($response);
echo $json_response;
}
?>
The above script will accept the GET request and return output in the JSON format.
I have created all these files in folder name rest, now you can get the transaction information by browsing the following URL.
http://localhost/rest/api.php?order_id=15478959
You will get the following output.
Above URL is not user friendly, therefore we will rewrite URL through the .htaccess file, copy paste the following rule in .htaccess file.
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?order_id=$1 [NC,L]
Now you can get the transaction information by browsing the following URL.
http://localhost/rest/api/15478959
You will get the following output.
2. Consume REST API in PHP
To consume a REST API, follow these steps:
- Create an Index File with HTML Form
- Fetch Records through CURL
1. Create an Index File with HTML Form
<form action="" method="POST">
<label>Enter Order ID:</label><br />
<input type="text" name="order_id" placeholder="Enter Order ID" required/>
<br /><br />
<button type="submit" name="submit">Submit</button>
</form>
2. Fetch Records through CURL
<?php
if (isset($_POST['order_id']) && $_POST['order_id']!="") {
$order_id = $_POST['order_id'];
$url = "http://localhost/rest/api/".$order_id;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
echo "<table>";
echo "<tr><td>Order ID:</td><td>$result->order_id</td></tr>";
echo "<tr><td>Amount:</td><td>$result->amount</td></tr>";
echo "<tr><td>Response Code:</td><td>$result->response_code</td></tr>";
echo "<tr><td>Response Desc:</td><td>$result->response_desc</td></tr>";
echo "</table>";
}
?>
You can do anything with these output data, you can insert or update it into your own database if you are using REST API of any other service provider. Usually in case of online transaction, the service provider provides status of payment via API. You can check either payment is made successfully or not. They also provide a complete guide of it.
Make sure CURL is enabled on your web server or on your localhost when you are testing demo.
I try my best to explain this tutorial as simple as possible.
If you found this tutorial helpful, share it with your friends and developers group.
I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks
Hi sir,
I am new to PHP and MySQL.
Your post helped me a lot to understand the rest API.
Could you please guide me on how to create a data insert and update page? There is only a demo for fetching data.
Please help me.
Thanks
Dear Manajit,
I am glad to know that you found my tutorials helpful. You can check out my tutorial about API which perform all CRUD operations via REST API https://www.allphptricks.com/laravel-10-rest-api-using-sanctum-authentication/
This is a great post! I’m a big fan of REST APIs and this post has given me a lot to think about.
I am glad that you like it.
This is a great post! I’m a big fan of REST APIs and this post has given me a lot to think about.
Thanks Kashif for the appreciation.
This is a bad example to follow. Your example leaves the database open to SQL injection attacks. To prevent this, you need to use prepared statements (with parameterized queries). While I’m sure you are well meaning by posting this sample of code, you are furthering misinformation and helping to encourage unsafe coding practices.
Dear Lauren,
Thanks for your input, I have shared prepared statements tutorial as well. I have also mentioned in the code that this is just for concept of API, indeed user will need to implement various security features before implement this on live project.
Thank u bro !
You are welcome Alex.
Attempt to read property “city_name” on null
Dear Vivek,
I didn’t use anthing like city_name, However, if you are using custom column so make sure that city_name data is not empty in DB.
Thank you.
You welcome 🙂
Thanks for detailed tutorial, I’m a beginner however i found super fun.
Please take into consideration to mention the following to make it more clear:
1. Localhost shall be updated on all files if you are not using Apache
2. Mac implementation requires some update in httpd.conf to allow php
3.Step of making api.php url more readable is not mandatory
Thank you so much for your amazing post
Thanks for your input.
Your create table code is wrong too many errors
Can you please share your errors?
Hi Javed
Great tutorial. I’m new to Php and trying to find best practices for seperating out AJAX and Php. I’ve recently written a website that’s going into production but to be honest I don’t like it. It’s full of Php functions that echo back html and css (bootstrap) alongwith the data it consumes from an API.
How would you suggest I go about having just the html, css and Jscript code in one area of a webroot directory, and in another folder, just the php code I can call to get the data and use with AJAX. Is this even possible with AJAX only?
Many thanks!
Jamie
Well, you should go with PHP framework like Laravel.
Thank You Javed!
You are welcome Dev.
Excuse me sir, How can i get all the orders from the endpoint and not just one specific order using http://localhost/rest/api/ as my endpoint
Dear Patrick,
Well for this purpose, you will need to get create another URL and fetch all the details there and passed in the associative array and then convert into JSON format.
Nice tutorial.
Would be nice to have perhaps another tutorial with post method ( for example to add an order from curl or api call).
Also would be nice to add a second parameter, and a third one optional ( could be or not).
Thanks again for your work
Super work Javed. Thumbs up and keep it up
Thanks Asif for the appreciation.
This is the tutorial for anyone who wants to get an understanding of an API
Thanks Peter for the appreciation.
Thank you so much for this Post
Thank you very much for this post, Javed! I’m new to working with APIs and was quite confused about how to consume and interact with the data before I’ve even received it, this cleared it all up and was simple to understand.
Thanks for the appreciation. I am glad that it helped you.
Hi Javed! thanks for informative tutorial. I just tried but with clean url its not working
could u provide me correct htacess where clean url works. For my rest of project clean url are working. Rewrite mode is enable and working fine.
Hi Omar,
Kindly check it on localhost, some web hosts does not work because some features are disabled therefore I would suggest you to kindly test it on localhost XAMPP, where all features are enabled to rewrite URL.
I already test it on localhost XAMPP, but still not working and show error
Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 35
Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 36
It seems like you are not able to fetch the data from database. Follow this tutorial to get the data from database correctly. https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
Why not use get_file_contents() instead of cURL?
You can use anyone that you like.
Thank you Javed. We really appreciate your work.
You welcome, thanks for the appreciation.
Its a nice tutorial on REST. I have a question, in your example(demo), when clicking the “submit” button, is the webpage reloading or it is working similar to AJAX ? Thank you.
I am not using AJAX in this code. it is simply reloading the page.
Hi, Its a nice explanation on REST API. I have a question please, how to pass 2 sets of items like this :
First set:
$response[‘order_id’] = 1;
$response[‘amount’] = 11;
$response[‘response_code’] = 111;
$response[‘response_desc’] = 1111;
2nd set:
$response[‘order_id’] = 2;
$response[‘amount’] = 22;
$response[‘response_code’] = 222;
$response[‘response_desc’] = 2222;
Much appreciated.
Suresh.
Create two input fields and pass both values in their respective REST URL and get the response of both and display them as per your need.
thank you deeply for your effort
Thanks Rasha for the appeciation.
This simplified all the complexities on REST API, made it so easy and comprehensive as possible. Great job!
Hi, it was really simple to understand.
Is it possible to add a “token” so that no one can misuse the API ?
Hola 🙂 No ubico el archivo htaccess tengo apserver, de antemano gracias! saludos!!
htaccess file will not be visible via Cpanel, connect to your server using FileZilla FTP to view htaccess file.
Hi thanks for the great tutorial. How can i use PDO statement instead of mysqli_query in your application?
Hello good friend
When we comment on you, you are disrespectful by not responding
good luck
Hi Reza,
This is my personal blog where I shared tutorials for free, I have several other projects that I am working on, this is why I am not always able to reply each comment. However, I try my best to reply as soon as possible.
I like this tutorial, thanks a lot, this is the simplest tutorial for API
Great article! I like the way you make things simple!
Thanks Christopher for the appreciation.
I’m beginner and it was useful to me and i learned it
Hi Shalini,
Thanks for the appreciation.
Hi 🙂 , and thanks for your awesome and beginner friendly tutorial.
this tutorial ‘ll be “great”, if you implement some basic validation and Sanitization.
Yes you are right, although the sole purpose of this tutorial is to give the basic overview that how things work. I do recommend to use validations before using it for live environment.
good post. but sir, can you give me full tutorial of api?
Sir,
why don’t you explain the same thing in you tube, by taking the reference of this website.
so that We can understand the concept very much clear, because in video we can see what actually you are doing.
If you do it, it’s really helps a lot of beginners, like me who don’t know, about api’s…
If you do a video on this please let me know Sir.
I am waiting for your responce…
Dear Aathreya,
Thanks for the suggestion, if i will have some time then i will surely make video tutorials.
Pls what is your YouTube channel name
I don’t have yet.
You need one bro
thankyou can you also tell how to consume api’s of google ,flickr etc
thank you, and
how to get update_date_time result in the table
$result->data($result->update_date_time) is not working
{
“success”: true,
“message”: “Success”,
“fulldata”: {
“update_date_time”: “2020-03-17 08:14:26”,
“local_new_cases”: 10,
}
}
Hi, thanks for the post, very helpful. I tried it, but did not work in the first attempt. It threw an internal server error. With some trial and error I got it to work by adding the following line to the .htacess file:
RewriteCond %{REQUEST_FILENAME} !-f
Thought it might help someone out there.
Thanks to share Mano 🙂
How to make link (URL) for our created REST API So that anybody can use it.Now I can make REST API But How to make URL (lINK) for it
Thank u for sharing Knowledge you Knowledge Sir
You welcome, I am glad that you found it helpful.
Sir please help me how to create login api can you please guide me
Nice simple api tutorial Sir, Thank you.
Dear Shahbaz, Thanks for the appreciation.
if i type numbers in the api it works, but if i type names, there are no results, why?
Because i made it for numbers only, if you want to make it for string then you will need to do everything for string.
Hi Javed, How to change the numbers to string? just change in the database structure?
Are you talking about Order ID?
What to change it to work with strings , like I have changed order id (int) to usr_msg (varchar) in database , but when I update the code and try using it , it sends a error . So How to change it to work with strings and what to change?
If you can share the error so I can help you more better direction.
Can you please make a tutorial, on how to make api for inserting data in database table through api.
Great post brother. thanks i like your simple coding. can you also put code to post API.
Structure will be changed if you want to user post form method on API, normally it is easily done via GET method, but if you want to do it, so yes it is possible but you will need to submit form this will create problem for you. How will you define the post form in post method? Therefore GET method is recommended here.
i unable to work under IIS using htaccess
Thanks!
Clear and objective!
Great job.
Thanks Ubirajara for the appreciation.
Great work, Javed. I’m trying to embed a playlist from a music streaming site into a website I’m building. I’m still finding it difficult to implement even after going through this article. Please can you make a tutorial about that? It will be a great favor to me if you do.
Amazingly Great job. These two points are well covered; “Consume REST API in PHP” and “Create a Database Connection”. Thanks for sharing this topic “Create and Consume Simple REST API in PHP”. The best part is the article has all the practical detailing! Keep sharing
Thanks Soha for the compliment.
Hi, have some tricky challenge is here , shall we talk now?
Great work Sir
But how to consume update a record API. I mean how to pass a json to API to update a record.
Well i didn’t write any tutorial about it, usually API is not for updates but if you need it so yes it is possible.
simple but perfect. thank you
Thanks Floriano
Thanks You so much Mr. Javed Ur Rehman for this blog, can you please mention, how to insert/update and delete the data into/from the database.
You welcome Muhammad Aquib, for insert, view, update, and delete, kindly check out my tutorial here https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
Please remove this post
It fails on numerous points of best practise and fundamental security.
You have managed to create an article advising people to write code which features XSS & SQL Injection vulnerabilities, as well as not being particularly robust and prone to errors.
You should never be outputting database error messages straight to the user
You should be using prepared queries to parameterize user input going into the database to make it safe from injection
You should be using html escaping (html_special_chars or htmlentities) before outputting any user input to a web browser.
Kindly read my post title again, this is just simple tutorial example which means as simple as possible, yes you will need to secure your program too, this is only for basic concept for newcomers.
well, can i see your examples? being rude and selfish is common in all the worlds… virtual or face to face.
dear Rehman,
i’ve apreciated your tuto.
i’m new in API development with PHP. i’m goint to ask a ridiculos questions:
i was trying to define a variable containing the currant date, that i would use to build my insert request in the API source code.
i’ve done that in my API:
$curDate= now();
but it generating an error.
i do not understand why?
should i always call the API with this current date as a parameter?
no system function can be called in the API source code?
thank you for your highlighting.
Moussa
regards
do we have to install mysqli to execute this code ??
If you do not have mysqli then yes this code is not going to work, you will require mysqli extension.
Javed excelent tutorial !
How do i adapt it to receive a Json input that contains several input values ?
Thank you so much from Argentina!
Hi sir, how if get API from other web ?
Yes API is actually made for sharing purpose, we mostly use other websites API’s for integration with our website.
thanks, very useful tutorial.
You welcome Dank
Notice: Trying to get property ‘order_id’ of non-object in C:\xampp\htdocs\rest\index.php on line 35
Notice: Trying to get property ‘amount’ of non-object in C:\xampp\htdocs\rest\index.php on line 36
Notice: Trying to get property ‘response_code’ of non-object in C:\xampp\htdocs\rest\index.php on line 37
Notice: Trying to get property ‘response_desc’ of non-object in C:\xampp\htdocs\rest\index.php on line 38
You can not use them, if you CURL is not enabled on your server. Also make sure that your database connection is working fine too.
Hi Javed,
I want to know how I can make this API get database credentials from a client side a shown below.
// Enter your Host, username, password, database below.
$con = mysqli_connect(“localhost”,”{$db_username}”,”{$db_pass}”,”{$db_name}”);
if (mysqli_connect_errno()){
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
die();
}
so how can I store those variables($db_username,$db_pass,$db_name) on the index.php file?
You do not need credentials in API, API are used to interact with database, mostly to view data or if they gave you access, you can update the data too.
You can see in my tutorial, it consist of two section, create and consume so if you are consuming API, you will get API to consume that do not required database credentials.
Thanks a lot ! I liked this post so much.
I have downloaded your code and it works fine in my testing environment, after updated “http://localhost/rest/api/” to “”http://localhost/rest/api.php?order_id=”.
when we refresh the page records were still there on the page , how to remove the records on refresh.
If you are sending order id it will fetch the record, keep in mind that you are fetching data using API, if you were using form submit method so records can be vanish after refresh.
where i have to link the curl code ie 2. Fetch Records through CURL
For testing run it on browser directly, if it is working fine use it in the code like i did in form submission page, download my tutorial and run it.
Hi sir my fields are shown null value please find out this. And also explain how i set my header.
{“order_id”:null,”amount”:null,”response_code”:400,”response_desc”:”Invalid Request”}
Guruveer you are getting Invalid Request, did you try to copy paste the same tutorial which i provided in download link? or you have made change in it? You are getting null because you are doing invalid request.
table does not display data but data store in array but it not display data on table view
I am actually fetching data from database, kindly make sure you have data in db and then fetch it simply and print array using print_r() function to check if you have data or not.
Are there any sources that fully explain this?
Hi Ahmad,
Well this is all my code, you can learn more about it by searching on Google. I tried my best to explain things as simple as possible.
Hi can u send how to update the data…..
insert,delete and getting data easily by using above code..thanks but i have problem to update or PUT method
Thanks my man, i liked this post so much.
You welcome Isaac M Machakata. 🙂
How can i fix this error ??
Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 32
Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 33
Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 34
Notice: Trying to get property of non-object in C:\xampp\htdocs\rest\index.php on line 35
It seems like you are getting error on printing, first you should try to print the array, check if values are available in the array.
Try to close the function before the else statement and it will work fine
what is the benefit of using APIs instead of an simple php file for the operation ?
There is lot of benefit, now a days data sharing is very common, for example suppose you are going to integrate online payment system and you need to send or fetch data from online payment server which is paid service, they will provide you API for this purpose, they will not give you their database credentials, i hope you find this helpful.
How to post to the database using Postman?
Sorry, i didn’t get you.
but how to update some data
This post is about consume REST API, to update, first you will need to create API which gives access to update any data.
You are incredible awesome man. Keep fast paced!
Thanks Joe 🙂
I am not getting the desired output for the .htaccess file. I am getting a invalid request response.What can I do to make it proper?Please help!
Although i am not using much code in htaccess file, i think you should create a fresh copy of htaccess file, sometimes issue raised due to corrupt htaccess file.
Incredible work, thank you, this is very useful to consume the information from a mobile app.
You welcome Pedro, if you found this helpful share it with your friends and also like our pages to keep update of our new posts.
Thank you, thank you, thank you. I really understood your explanation and I sincerely appreciate it. I have been looking for a way to create and consume REST API. This has shed some light to me. I will appreciate if I can get more videos or tutorial on REST API. I want to be very good in API.
Thanks for the appreciation.
Hi….
I have create api for login and pass then click on button the redirect directly login…but login and pass not a login form that is other user login via other form…
Your problem is actually not clear to me, can you please explain in detail.