+++ Creating A Simple REST API in PHP - ShareurCodes
+++ Creating A Simple REST API in PHP - ShareurCodes
1 reader
REST (Representational State Transfer) is a way of accessing the web services. REST as an architecture style does not require processing and
is more simple and flexible than SOAP(Simple Object Access Protocol) which is another standards-based Web services access protocol
developed by Microsoft. REST is much easier and more widely used than SOAP (about 70% web services API uses REST API) and is the
newcomer to the block which seeks to fix all problems with SOAP. In this tutorial, I will show you the easiest method to create your own
REST API in PHP.
Before we start implementation details let's understand what is REST. We used REST API to fetch or give some information from a web
service. It is as simple as giving an HTTP GET or POST or PUT or DELETE request from the client (Mobile Application, A website etc.) to the
server to get some information from the server or to give some information to the server. The REST based web services can give output in
any format like Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS). The point is that
you can obtain the output you need in a form that’s easy to parse within the language you need for your application. A sample REST API
diagram is given below.
The JSON is the most common output format of REST API and we are going to make a REST API which accepts GET request and gives JSON
output. We will create a REST API which requests a particular product price over URL. The name of the object will be passed as parameter
and we will get the price of that product in JSON format. The tutorial consist of mainly 2 parts. The first part deals with the creation of REST
API in PHP and second part deals with consumption of REST API in PHP.
5 if(!empty($_GET['name']))
6 {
7 $name=$_GET['name'];
8 $price = get_price($name);
9
10 if(empty($price))
11 {
12 response(200,"Product Not Found",NULL);
13 }
14 else
15 {
16 response(200,"Product Found",$price);
17 }
18
19 }
20 else
21 {
22 response(400,"Invalid Request",NULL);
23 }
24
25 function response($status,$status_message,$data)
26 {
27 header("HTTP/1.1 ".$status);
28
29 $response['status']=$status;
30 $response['status_message']=$status_message;
31 $response['data']=$data;
32
33 $json_response = json_encode($response);
34 echo $json_response;
35 }
The above script file is responsible for dealing with HTTP GET requests and delivering JSON output to the user. We need to specify the
content type of this file as JSON since it gives JSON output for standardization. The API uses data.php file to fetch price of particular
product.
1 <?php
2
3 function get_price($name)
4 {
5 $products = [
6 "book"=>20,
7 "pen"=>10,
8 "pencil"=>5
9 ];
10
11 foreach($products as $product=>$price)
12 {
13 if($product==$name)
14 {
15 return $price;
16 break;
17 }
18 }
19 }
For simplicity, i am fetching the price from an array instead of the database. When you are creating API in real world you need to fetch data
from the database. If you are new to PHP then using PDO with Prepared Statement is the best way to fetch data from the database. I made
a details post about PDO with Prepared Statement and you can look at it by visiting the following link.
Now you can get the product information by visiting following URL.
1 http://localhost/projectname/api.php?name=pen
But you can see that above URL is not standardized. So we can standardize the URL by using a simple .htaccess file to rewrite URL in apache
server.
The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be
processed. Use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters
appear as upper-case or lower-case in the matched URI.
1 http://localhost/projectname/api/pen
Now we can get price details in our PHP website by calling REST API as HTTP GET request through CURL as given below.
1 <?php
2 if(isset($_POST['submit']))
3 {
4 $name = $_POST['name'];
5
6 $url = "http://localhost/projectname/api/".$name;
7
8 $client = curl_init($url);
9 curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
10 $response = curl_exec($client);
11
12 $result = json_decode($response);
13
14 echo $result->data;
15 }
16 ?>
Remember to set CURLOPT_RETURNTRANSFER as true since we need to give CURL output to a variable and normally CURL will not allow to
store its output in a variable. A simple JSON decode will give us the price.
13 <div class="container">
14 <h2>Rest API Client Side Demo</h2>
15 <form class="form-inline" action="" method="POST">
16 <div class="form-group">
17 <label for="name">Name</label>
18 <input type="text" name="name" class="form-control" placeholder="Enter Product Name" required/>
19 </div>
20 <button type="submit" name="submit" class="btn btn-default">Submit</button>
21 </form>
22 <p> </p>
23 <h3>
24 <?php
25 // Refer above PHP code
26 ?>
27 </h3>
28 </div>
29 </body>
30 </html>
The current .htaccess doesn't give support for integers as product name, hence it would throw a 404-Not found an error if you use an
integer as the product name. So update the rewrite rule as below.
If you have any suggestions or doubts please comment below and I try will respond to every one of you as early as possible.
Similar Posts
jQuery UI Autocomplete How to prevent others Send Real Time How to Prevent Shell Create a Simple Online Create
with … from accessing your … Notification to … Attack in Image File … Readers Count … upload
7 years ago • 9 comments 7 years ago • 2 comments 7 years ago • 6 comments 7 years ago • 1 comment 5 years ago • 1 comment 6 years
I will show you how to make Most of the web developer How to send the free real- The Command Injection How to make a simple real- I this tu
a live search like IMDB forgot to secure their assets time notifications to real Vulnerabilities are one of the time online reader badge how to
search box with custom … folders in public directory. … time clients through … most common types of … react component for your … image u
43 Comments
1 Login
Name
S
Scott V − ⚑
5 years ago
Geordy, thanks for this example. So many of the examples out there require a lot of prerequisites
(OOP, MySQL, etc.) and end up getting lost in the weeds. This example is succinct and focused.
Also, the .htaccess portion was a huge time saver as I'm new to Apache and needed a way to make
the URL simple for the users. Thanks!
9 0 Reply ⥅
mahmoudzalt − ⚑
4 years ago
It's 2020, and there's still no better option than using this awesome API framework http://apiato.io
(built with PHP on top of Laravel).
2 0 Reply ⥅
J
JayGreentree > mahmoudzalt
− ⚑
4 years ago edited
0 0 Reply ⥅
W
William Okafor − ⚑
6 years ago
Little contribution,
The .htaccess doesn't give support for integers as product name, hence it would throw a 404-Not
found error if you use an integer as the product name.
2 0 Reply ⥅
3 0 Reply ⥅
mahmoudzalt − ⚑
7 years ago
2 0 Reply ⥅
Aitizaz Hassan − ⚑
6 years ago
really good materal to understanding the basic api concepts thanks a lot.
2 1 Reply ⥅
D
DEEPIKA KUPPILI − ⚑
5 years ago
1 0 Reply ⥅
D
dilip − ⚑
5 years ago
i have a confusion that where i put .htaccess file and what name i have to provide. its only
.htaccess or filename.htaccess
1 0 Reply ⥅
Just .htaccess and you need to put it in public folder where index.php file preset. If you
hosted it in godaddy or some hosting providers you need to put in inside public_html file.
htaccess file no file name just extension. file begin with dot is to indicate that they are
hidden files by default. You can use .htaccess file to manipulate some default apache
configurations.
3 0 Reply ⥅
Nhin Nguyễn − ⚑
6 years ago
Thanks a lot.
1 0 Reply ⥅
Daniel E Delgado D − ⚑
6 years ago
1 0 Reply ⥅
obamafone − ⚑
3 years ago
Yes this works. Thanks for this! In a day I had a full up API to my SW DB running. When I started I
really didn't understand anything about APIs.
0 0 Reply ⥅
brent e − ⚑
3 years ago
And on the data.php file, if you want it to return the product name, then a space, then the price, try
this:
0 0 Reply ⥅
brent e − ⚑
3 years ago edited
This worked for me. I put an API directory on my domain like this https://mydomain.com/api
Then I changed the .htaccess at the top level of the domain with the following:
0 0 Reply ⥅
R
reza − ⚑
R 4 years ago
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'https://yousite.com/api/api... );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-Type' =>'application/json' ) );
curl_setopt( $curl, CURLOPT_POSTFIELDS, 'license=' . $youVariable
.'&secret_key=reza_tntlogin&domain=' . $_SERVER['SERVER_NAME'] );
curl_setopt( $curl, CURLOPT_TIMEOUT, 400 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
$result = json_decode( curl_exec( $curl ) );
curl_close( $curl );
0 0 Reply ⥅
Y
yurimodin − ⚑
4 years ago
the .htaccess did not work for me at all......I ended up with this placed in an .htaccess file inside the
/api/ directory RewriteRule ^([0-9a-zA-Z_-]*)$ /api/api.php?name=$1 [R=301,NC,L]
0 0 Reply ⥅
विनोद अनुज − ⚑
4 years ago
0 0 Reply ⥅
Dendy B. Sulistyo − ⚑
5 years ago
Thanks, Geordy
can you show the .htaccess to allow show all data ?
thank you
0 0 Reply ⥅
Just Syok − ⚑
6 years ago
hello there,
i like to use SOAP style because user may view WSDL. is there in REST user can see something like
wsdl. tq
0 0 Reply ⥅
Hi Just,
If you prefer SOAP then you can easily implement SOAP Web service by using a free open
source SOAP Toolkit for PHP named NuSOAP for creating XML. The WSDL file will be
created by the server on the go automatically by NuSOAP library.
To know more about how to create a SOAP Web Service please visit
https://shareurcodes.com/bl...
0 0 Reply ⥅
Z
Zalak Thakkar − ⚑
6 years ago
Great Work! I have done exact way. But my problem is authenticating client server from my server.
Please loot at the link for issue:
https://stackoverflow.com/q...
0 0 Reply ⥅
M
Mohd Ryza Zakaria − ⚑
6 years ago
0 0 Reply ⥅
D
Dani − ⚑
6 years ago edited
Hi,
Thanks for this useful article. The .htaccess file still not working. I still have to call the api using:
Knowing that I created the .htaccess file and I tried placing it inside the www directory, inside the
project itself, but nothing worked.
Hope you can help me on this..
0 0 Reply ⥅
V
Vyacheslav “MasterCrew” Artemo − ⚑
6 years ago edited
Sorry, but i don't understand... How many files will be in example2 "2) Consuming REST API In PHP"
and what are the names of these files... It was't described... Or i can't translate it. Pls help me.
0 0 Reply ⥅
Hi the first file ie api.php is the core file which does all API feching operations. The second
file data.php is created to store some sample data's in a array for simplecity. In real-life
you don't store data in files,so you need to fetch data from database.
Now for getting output ie to test whether our API work we create a sample.php file which
call our rest API through curl. It is the third file in the above example.
Please note, since it is a get request simply copy and pasting url will work for testing. If it
a post,put or delete requests then use postman.
0 0 Reply ⥅
N
naliseth mencias − ⚑
6 years ago
Hello, i have a question. i created the data.php and api.php, when i put on the browser for example :
http://localhost/rest/api/book. i receive a error message: SyntaxError: JSON.parse: unexpected
character at line 1 column 1 of the JSON data
Please, What can i do it?
0 0 Reply ⥅
Hi this happen because there is some syntax error with JSON . Are you passing it to
JavaScript JSON.parse function ?. Please post your complete code in stack overflow and
share the link here. I can't debugg your code without seeing it.
0 0 Reply ⥅
N
naliseth mencias > Geordy James
− ⚑
6 years ago
//api.php
0 0 Reply ⥅
N
naliseth mencias > Geordy James
− ⚑
6 years ago
//--------data.php---------
20,
"pen"=>10,
pe 0,
"pencil"=>5
];
foreach($products as $product=>$price)
{
if($product==$name)
{
return $price;
break;
}
}
}
?>
//--------api.php---------
0 0 Reply ⥅
N
naliseth mencias > Geordy James
− ⚑
6 years ago
Hello, thanks for reply my message. I use the example on this page api.data and
data.php
0 0 Reply ⥅
Ankush Shinde − ⚑
6 years ago
0 0 Reply ⥅
0 0 Reply ⥅
S
Shruti Upari − ⚑
6 years ago edited
Hello Geordy!! I have been working on small project of and I wanted to know how to work on reset
password link in core php. if you could guide me it would be of great help. Simple guidance I
require as I'm new to Api
0 0 Reply ⥅
Hi Shruti Upari,
The simplest way according to me is to create a table named password_resets with fields
email, token and created_at(current timestamp) and then when a user submit his valid
email in password reset form create a unique token (ie you can use this formula
substr(hash('sha256', mt_rand() . microtime()), 0, 20); ) and insert it into password_resets
table and then send him the link to reset the password along with this token as url get
parameter.
Now when user click this link accept his email and new password and token( you will get
this from url) validate it with password_reset table and change the password.
Remember after successfully reset the password delete his entry from password_resets
table for security reason.
This method may seems to be little complex to you if you are new to PHP but you can
reuse this module in other future projects you may create. If you need more assistant then
email me at [email protected]
0 0 Reply ⥅
S
Shruti Upari > Geordy James
− ⚑
6 years ago
0 0 Reply ⥅
Dominik Lepeták − ⚑
7 years ago
Hey Geordy, I am pretty new with api and I am using Atom and it's not working. Any tips?
0 0 Reply ⥅
The Atom is just a text editor and it will not cause you any problems and I am using
Sublime text. Can you specify your errors by opening google chrome console and network
tab (red one). I need more information about error message to find exact cause.
0 0 Reply ⥅
N
Nadav Morneo − ⚑
7 years ago
Thanks
0 0 Reply ⥅
0 0 Reply ⥅
Adeola Oladoja − ⚑
6 years ago
Please Sir, I am new to this API, I am having issue at this .htaccess. Its not working here
0 1 Reply ⥅
Hi Adeola what is the exact issue you are facing. Did it work with original url. If you are
using linux system then you need to allow overriding of htaccess in Apache Configuration.
Visit following link to know how to do that https://stackoverflow.com/a...
0 0 Reply ⥅
Oh es
Tags : PHP
No of Views : 339305
Popular Posts