How to Build REST API Using PHP

Create REST API in PHP

API stands for Application Programming Interface and the idea behind API is to connect different applications irrespective of their platforms to share information. Generally, API takes requests from different applications, processes it and gives back the response.


What is REST API?

REST stands for Representational State Transfer and it means that the request and the response should contain a representation of the information i.e., should be in a certain format. So basically, the requests must use proper HTTP methods and the response must be in a proper format like JSON or XML instead of plain text.
REST API is nothing but a normal API with a set of principles. We need to follow a set of rules while creating and consuming REST API.
The rules include the following :
1. Use appropriate HTTP methods while performing API calls. The following are the four primary HTTP methods which should be used to send and receive API requests.
      a. GET      – To read single or multiple records.
      b. POST    – To create a new record.
      c. PUT      – To Update a record.
      d. DELETE – To delete a record.

1. POST Method

Name of a page will be "insertAPI.php".

<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$conn = mysql_connect("localhost","root","password");
mysql_select_db("Products", $conn);
//Get Data
$productId = mysql_real_escape_string($_REQUEST["pId"]);
$productName = mysql_real_escape_string($_REQUEST["pName"]);
$productPrice = mysql_real_escape_string($_REQUEST["pPrice"]);
// Insert data into data base
$sql = "INSERT INTO products.products_list (product_Id, product_Name, product_Price) VALUES ('$productId', '$productName', $productPrice);";
$qur = mysql_query($sql);
if($qur)
{
$json = array("status" => 1, "msg" => "Done Product added");
}
else
{
$json = array("status" => 0, "msg" => "Error adding Product");
}
}
else
{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
 
@mysql_close($conn);
 
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>

2. PUT Method

Name of a page will be "updateAPI.php".

<?php
if($_SERVER['REQUEST_METHOD'] == "PUT")
{
$conn = mysql_connect("localhost","root","password");
mysql_select_db("Products", $conn);
//Get Data
$productId = mysql_real_escape_string($_REQUEST["pId"]);
$productName = mysql_real_escape_string($_REQUEST["pName"]);
$productPrice = mysql_real_escape_string($_REQUEST["pPrice"]);
// update data into data base
$sql = "UPDATE products.products_list SET product_Name='$productName', product_Price=$productPrice where product_Id='$productId'";
$qur = mysql_query($sql);
if($qur)
{
$json = array("status" => 1, "msg" => "Done Product updated");
}
else
{
$json = array("status" => 0, "msg" => "Error updating Product");
}
}
else
{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
 
@mysql_close($conn);
 
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>

3. DELETE Method

Name of a page will be "deleteAPI.php".

<?php
if($_SERVER['REQUEST_METHOD'] == "DELETE")
{
$conn = mysql_connect("localhost","root","password");
mysql_select_db("Products", $conn);
//Get Data
$productId = mysql_real_escape_string($_REQUEST["pId"]);
// delete data from database
$sql = "DELETE from products.products_list where product_Id='$productId'";
$qur = mysql_query($sql);
if($qur)
{
$json = array("status" => 1, "msg" => "Done Product Deleted");
}
else
{
$json = array("status" => 0, "msg" => "Error deleting Product");
}
}
else
{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
 
@mysql_close($conn);
 
/* Output header */
header('Content-type: application/json');
        echo json_encode($json);
?>

4. GET Method

Name of a page will be "getAPI.php".

<?php
if($_SERVER['REQUEST_METHOD'] == "GET")
{
$conn = mysql_connect("localhost","root","");
mysql_select_db("Products", $conn);
//Get Data
$productId = mysql_real_escape_string($_REQUEST["pId"]);
// update data into data base
$sql = "SELECT * from products.products_list where product_Id='$productId'";
$qur = mysql_query($sql);
if($row = mysql_fetch_array($qur))
{
$json = array("productId" => "$row[0]", "productName" => "$row[1]","productPrice" => "$row[2]");
}
else
{
$json = array("status" => 0, "msg" => "Product Not found!");
}
}
else
{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
 
@mysql_close($conn);
 
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>

Consuming a REST API using PHP

We will be using cURL here to consume the API. There are built-in functions for cURL in PHP and the following are the functions we will be using.
a.Establish a connection – curl_init()
b.Add request data – curl_setopt()
c.Send the request – curl_exec()
d.Close the connection – curl_close()

3. The following code is used to get a product.

<?php

if(isset($_REQUEST["pId"]))
{
$pId = $_REQUEST["pId"];
$url = "http://localhost/web/getAPI.php?pId=".$pId;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_HTTPGET,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response_json = "".curl_exec($ch);
curl_close($ch);
$response = json_decode($response_json,true);
$msg = $response["productId"];

}

?>

2. The following code is used to update a product.

<?php

if(isset($_REQUEST["pIdUpdate"]) && isset($_REQUEST["pNameUpdate"]) && isset($_REQUEST["pPriceUpdate"]))
{
$pId = $_REQUEST["pIdUpdate"];
$pName = $_REQUEST["pNameUpdate"];
$pPrice = $_REQUEST["pPriceUpdate"];
$url="http://localhost/web/updateAPI.php?pId=".$pId."&pName=".$pName."&pPrice=".$pPrice;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,'PUT');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response_json = "".curl_exec($ch);
curl_close($ch);
$response = json_decode($response_json,true);
$msg = $response["msg"];
if($msg == "Done Product updated")
{
header("location:index.php?update=1");
}
else if($msg == "Error updating Product")
{
header("location:index.php?unupdate=1");
}
}

?>

3. The following code is used to insert a product.

<?php

if(isset($_REQUEST["pId"]) && isset($_REQUEST["pName"]) && isset($_REQUEST["pPrice"]))
{
$pId = $_REQUEST["pId"];
$pName = $_REQUEST["pName"];
$pPrice = $_REQUEST["pPrice"];
$url="http://localhost/web/insertAPI.php?pId=".$pId."&pName=".$pName."&pPrice=".$pPrice;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response_json = "".curl_exec($ch);
curl_close($ch);
$response = json_decode($response_json,true);
$msg = $response["msg"];
if($msg == "Done Product inserted")
{
header("location:index.php?insert=1");
}
else if($msg == "Error inserting Product")
{
header("location:index.php?uninsert=1");
}
}

?>

4. The following code is used to delete a product.

<?php

if(isset($_REQUEST["pId"]))
{
$pId = $_REQUEST["pId"];
$url = "http://localhost/web/deleteAPI.php?pId=".$pId;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,'DELETE');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response_json = "".curl_exec($ch);
curl_close($ch);
$response = json_decode($response_json,true);
$msg = $response["msg"];
if($msg == "Done Product Deleted")
{
header("location:index.php?delete=1");
}
else if($msg == "Error deleting Product")
{
header("location:index.php?undelete=1");
}
}

?>

Comments

Popular posts from this blog

Tree

AVL (Adelson-Velskii and Landis) Trees