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.

    REST API Diagram

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.

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

if(!empty($_GET['name']))
{
	$name=$_GET['name'];
	$price = get_price($name);
	
	if(empty($price))
	{
		response(200,"Product Not Found",NULL);
	}
	else
	{
		response(200,"Product Found",$price);
	}
	
}
else
{
	response(400,"Invalid Request",NULL);
}

function response($status,$status_message,$data)
{
	header("HTTP/1.1 ".$status);
	
	$response['status']=$status;
	$response['status_message']=$status_message;
	$response['data']=$data;
	
	$json_response = json_encode($response);
	echo $json_response;
}

 

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.

<?php

function get_price($name)
{
	$products = [
		"book"=>20,
		"pen"=>10,
		"pencil"=>5
	];
	
	foreach($products as $product=>$price)
	{
		if($product==$name)
		{
			return $price;
			break;
		}
	}
}

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.

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.

RewriteEngine On    # Turn on the rewriting engine

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.

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.

<?php
	if(isset($_POST['submit']))
	{
		$name = $_POST['name'];
		
		$url = "http://localhost/projectname/api/".$name;
		
		$client = curl_init($url);
		curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
		$response = curl_exec($client);
		
		$result = json_decode($response);
		
		echo $result->data; 
	}
   ?>

 

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.

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

<div class="container">
  <h2>Rest API Client Side Demo</h2>
  <form class="form-inline" action="" method="POST">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" name="name" class="form-control"  placeholder="Enter Product Name" required/>
    </div>
    <button type="submit" name="submit" class="btn btn-default">Submit</button>
  </form>
  <p>&nbsp;</p>
  <h3>
  <?php
	// Refer above PHP code
   ?>
  </h3>
</div>
</body>
</html>

 

If you have any suggestions or doubts please comment below and I try will response to every one of you as early as possible.

Tags : PHP




Web development
24 Nov 2017 01:35am
PHP
15197