0% found this document useful (0 votes)
28 views

+++ Creating A Simple REST API in PHP - ShareurCodes

Uploaded by

Luis Cortes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

+++ Creating A Simple REST API in PHP - ShareurCodes

Uploaded by

Luis Cortes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Abre la Caja Negra de PMAX


Más Información para Gestionar Pmax: KPIs por canales, términos de
búsqueda

Dolnai Technology Aplicar

HOME BLOGS CATEGORIES TAGS ABOUT CONTACT

1 reader

Creating a simple REST API in PHP

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.

LET'S START CODING

1) CREATION OF REST API IN PHP

The complete code inside api.php file is given below.


1 <?php
2 header("Content-Type:application/json");
3 require "data.php";
4

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.

The complete code for the data.php file is given below.

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 complete code for .htaccess file is given below.

1 RewriteEngine On # Turn on the rewriting engine


2

3 RewriteRule ^api/([a-zA-Z_-]*)$ api.php?name=$1 [NC,L]

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.

So now we can access product information by visiting following URL.

1 http://localhost/projectname/api/pen

2) Consuming REST API In PHP

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.

The HTML form is given below for references.


1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <title>Rest API Client Side Demo</title>
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1">
7 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
8 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
9 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
10 </head>
11 <body>
12

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>&nbsp;</p>
23 <h3>
24 <?php
25 // Refer above PHP code
26 ?>
27 </h3>
28 </div>
29 </body>
30 </html>

UPDATE 25th Feb 2018

A contribution from William Okafor

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.

1 RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?name=$1 [NC,L]

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

Send Push Notification to Users Using Firebase Messaging Service


in PHP
Published at 18th Mar 2017
ALSO ON SHAREURCODES

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

G Join the discussion…

LOG IN WITH OR SIGN UP WITH DISQUS ?

Name

 8 Share Best Newest Oldest

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

I use Processwire for building APIs

0 0 Reply ⥅

W
William Okafor − ⚑
6 years ago

Awesome stuff here!

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.

i used this as me rewrite rule and everyone went home happy

RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?name=$1 [NC,L]

2 0 Reply ⥅

Geordy James Mod > William Okafor


− ⚑
6 years ago

Thank you William for your contribution. Really appreciate that.

3 0 Reply ⥅

mahmoudzalt − ⚑
7 years ago

Nice article, thanks.


I'm using APIATO (https://github com/apiato/a it's a flawless framework for building scalable and
I m using APIATO (https://github.com/apiato/a... it s a flawless framework for building scalable and
testable API-Centric Apps with PHP and Laravel.

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

where we add these php files

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 ⥅

Geordy James Mod > dilip


− ⚑
5 years ago

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

Fantastic article!!, Thanks for the info!!!

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:

return $name . " " . $price;

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:

# For API test


RewriteEngine On # Turn on the rewriting engine
RewriteRule ^api/([0-9a-zA-Z_-]*)$ /api/api.php?name=$1 [NC,L]

This enabled https://mydomain.com/api/pen to return a value of


{"status":200,"status_message":"Product Found","data":10}

0 0 Reply ⥅

R
reza − ⚑
R 4 years ago

Hello, can you help?


Return the value of this variable exactly with rest api
file api.php{ ?????? }

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

if ($result->status == 100) {//The correct process


}else{
echo '<div class="alert alert-danger"> Oh, something went wrong : ' .
$result->status . '</div>';
}

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

Its very useful post. Thank you a lot.


I'm new to API's and this article helped me to understand it.

If possible, please guide me a bit further!


From this article I learnt to get a particular data with respect to posted value. But I got confused for
how can I get multiple data about the posted value. Like, if I need not only price of a book but also
its dimension, weight, writer, etc, how can I do that?

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 ⥅

Geordy James Mod > Just Syok − ⚑


6 years ago

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

thanks great article.

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:

http://localhost/projectname/api.php?name=pen instead of http://localhost/projectname/api/pen.

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

Note that I'm using wamp server (Windows OS)


Best Regards.

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 ⥅

Geordy James Mod > Vyacheslav “MasterCrew” Artemo − ⚑


6 years ago

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 ⥅

Geordy James Mod > naliseth mencias


− ⚑
6 years ago

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

I want to create the web api in open cart framework .

0 0 Reply ⥅

Avata This comment was deleted. −


Geordy James Mod > Guest
− ⚑
6 years ago

Thank you Peter for pointing out the error.

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 ⥅

Geordy James Mod > Shruti Upari


− ⚑
6 years ago

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

Thanks !!! Will try it out the way u hv suggested me

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 ⥅

Geordy James Mod > Dominik Lepeták


− ⚑
7 years ago

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 ⥅

Geordy James Mod > Nadav Morneo − ⚑


7 years ago

You are welcome...

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 ⥅

Geordy James Mod > Adeola Oladoja − ⚑


6 years ago

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 ⥅

Adeola Oladoja > Geordy James − ⚑


6 years ago

Oh es

 Category : Web development

 Created At : 21st Apr 2017 07:22:42 AM

 Last Updated : 25th Feb 2018 08:33:33 AM

 Tags : PHP

 No of Views : 339305

<< SEE ALL POSTS


Geordy James
I work as a Full Stack Javascript Developer, developing professional applications in
React and Node.js.

Popular Posts

Creating a simple REST API in PHP

Published at 21st April 2017

Real time progress bar in PHP

Published at 1st March 2017

Send Push Notification to Users Using Firebase Messaging Service in PHP

Published at 18th March 2017

DataTables Server-side Processing in Laravel

Published at 26th March 2017

DataTables Server-side Processing with Custom Parameters in CodeIgniter

Published at 24th May 2017

DataTables Server-side Processing in CodeIgniter

Published at 5th May 2017


Design and Created By - Geordy James

You might also like