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/samsungWhen 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]