How To Create Simple REST API in PHP

Posted on

REST (Representational State Transfer) is one of way of accessing the web services. The REST API used by making HTTP GET or POST or PUT or DELETE request from the client side to the server to get or to put some information to the server. The REST based web services can give output in any format like CSV, JSON, RSS etc. So it is depend on requirement to which format you want to parse easily with your language. In this tutorial you will learn how to create simple REST API using PHP with demo. The tutorial explained in a very easy steps with live demo to get product details by making HTTP GET request and link download source code.

So let’s start the coding. We will have following file structure for REST API example.

  • index.php
  • read.php

Steps1: In this REST API example, we will read data from MySQL database. So using below table create statement, we will create items to store and get data.
CREATE TABLE `items` (
`id` int(11) NOT NULL,
`name` varchar(256) NOT NULL,
`description` text NOT NULL,
`price` int(255) NOT NULL,
`category_id` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Steps2:After creating MySQL database table, we will create db_connect.php file to make connection with MySQL database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phpzag_demos";
$conn = mysqli_connect($servername, $username, $password, $dbname);
?>

Steps3: As in this REST API example we will search product by making URL request. So in index.php, we will create FORM with input and search button.
<div class="container">
<h2>How To Create Simple REST API in PHP</h2>
<form class="form-inline" action="" method="POST">
<div class="form-group">
<label for="name">Search Item(Samsung, Sony, LG etc):</label>
<input type="text" name="name" class="form-control" placeholder="Enter Product Name" required/>
</div>
<button type="submit" name="submit" class="btn btn-default">Find</button>
</form>
</div>

Steps4: On Search Form submit, we will make REST API HTTP GET request through CURL to get product details. We will decode JSON response as the response get as JSON.

<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$url = "http://phpzag.com/demo/how-to-create-simple-rest-api-in-php/items/read/".$name;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
print_r($result);
}
?>

Steps5: Now finally in REST API script read.php, we will handle HTTP GET requests and return JSON output.

<?php
header("Content-Type:application/json");
include_once("../db_connect.php");
if(!empty($_GET['name'])) {
$name=$_GET['name'];
$items = getItems($name, $conn);
if(empty($items)) {
jsonResponse(200,"Items Not Found",NULL);
} else {
jsonResponse(200,"Item Found",$items);
}
} else {
jsonResponse(400,"Invalid Request",NULL);
}
function jsonResponse($status,$status_message,$data) {
header("HTTP/1.1 ".$status_message);
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response = json_encode($response);
echo $json_response;
}
function getItems($name, $conn) {
$sql = "SELECT id, p.name, p.description, p.price, p.created FROM items p WHERE p.name LIKE '%".$name."%' ORDER BY p.created DESC";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data[] = $rows;
}
return $data;
}
?>

The HTTP get request can be made through URL like below.

http://phpzag.com/demo/how-to-create-simple-rest-api-in-php/items/read/samsung

When HTTP GET request made using above URL, the product details get from database table using getItems() function and return as JSON encoded. If search not found in database then it return status message as “Items Not Found”.

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

9 thoughts on “How To Create Simple REST API in PHP

  1. Thanks for this post. I want to make an app, am using intel xdk Cordova, which is a native but don’t want it to be static rather dynamic. Can I use API to pull out information from the Database?

    I am using PHP and MySQL. Want my mobile app to get information from the database instead of just normal html, css, js.

  2. Thanks for this post. i want to make restful API using post not get. In this API will hit the post method not get method.
    I will use this API to get the information of the user from the database.

    thanks ,

  3. This is helpful for me.

    How to insert the data into database using this code can you please suggest any solution. I need to insert name, price, description,category_id. Can you please suggest any solution

Leave a Reply

Your email address will not be published. Required fields are marked *