SIMPLE RESTful API IN PHP FOR PRODUCT REVIEW AND RATING PROJECT

 SIMPLE RESTful API IN PHP FOR PRODUCT REVIEW AND RATING


step-by-step guidance

Today, we will learn how to create a simple REST API in php by taking a simple php project in which we store data in MYSQL database and fetch from it to display.

We will use this php project to create REST API to READ and INSERT data from/to database.

In this post, we will cover all these following topics one-by-one:

  • what is REST api
  • why do we need REST api
  • where REST api is used
  • file structure of project
  • simple php project on which we implement REST api
  • step-by-step execution of api


WHAT IS REST API?


REST (Representational State Transfer) is a system architecture that defines the set of methods to access the web services. The main goal of REST API is to create a system that can be used by different applications.

The REST API are created with CRUD (Create, Read, Update, Delete) operations. The REST API is consumed by making HTTP request (GET, POST, PUT or DELETE) from the client side. The API is implemented in way to return response in JSON or XML or any other format.

So if you’re working on application to work on different devices like Desktop, mobile etc, then you can create REST API with required operations to be accessed by different application like web application and Mobile application.

In this tutorial you will learn how Create Simple RESTful API with PHP and MySQL. We will implement REST API with CRUD operations to create items, read items, update items and delete items.

We will cover this tutorial step by step with live example to create RESTFul API to perform CRUD (Create, Read, Update, Delete) operations and consume REST API with HTTP request (GET, POST, PUT or DELETE) to play with items data.



WHT DO WE NEED REST API?


In many applications, REST API is a need because this is the lightest way to create, read, update or delete information between different applications over the internet or HTTP protocol. This information is presented to the user in an instant especially if you use JavaScript to render the data on a webpage.


WHERE REST API IS USED?


REST API can be used by any application that can connect to the internet. If data from an application can be created, read, updated or deleted using another application, it usually means a REST API is used.


FILE STRUCTURE OF THE PROJECT



product_review_and_rating

     include

                 config

     product_rating_api

                 class

                                 items

                 config

                                 core

                                 Database

                 items

                                 .htaccess

                                 create

                                 read

                                 read-average

                 shared

                                 utilities

     product_review_api

                 class

                                 items

                 config

                                 Database

                 items

                                 .htaccess

                                 create

                                 read

     index


PHP PROJECT ON WHICH WE IMPLEMENT REST API

I am going to make a simple PRODUCTS php project in which through simple html & php form ww take product details from the user like product name, product price and product description and on submit the form the product details will store at MYSQL DATABASE and all products details will fetched automatically from database to display below the form on the same webpage.


Step 1 - Create MYSQL Database Table


CREATE TABLE `product_rating` (
`id` int(11) NOT NULL AUTO INCREMENT,
`user_id` varchar(100) NOT NULL,
`product_id` varchar(100) NOT NULL,
`rating` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `product_review` (
`id` int(11) NOT NULL AUTO INCREMENT,
`user_id` varchar(100) NOT NULL,
`heading` varchar(500) NOT NULL,
`description` varchar(500) NOT NULL,
`product_id` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Step 2 - Insert Data For Demo In MYSQL Database Table


INSERT INTO `product_rating` (`id`, `user_id`, `product_id`, `rating`) VALUES
(1, 'user1', 'product1', '3'),
(2, 'user2', 'product2', '4'),
(3, 'user3', 'product3', '2'),
(4, 'user4', 'product4', '4'),
(5, 'user5', 'product5', '5'),
(6, 'user6', 'product6', '3'),
(7, 'user7', 'product7', '4');

INSERT INTO `product_review` (`id`, `user_id`, `heading`, `description`, `product_id`) VALUES
(1, 'user1', 'heading1', 'description1', 'product1'),
(2, 'user2', 'heading2', 'description2', 'product2'),
(3, 'user3', 'heading3', 'description3', 'product3'),
(4, 'user4', 'heading4', 'description4', 'product4'),
(5, 'user5', 'heading5', 'description5', 'product5'),

Step 3 - Create Database Connection for Php Project


define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'product_review_and_rating');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Step 4 - Create Frontend and Backend Connection for Php Project







OUTPUT




STEP-BY-STEP EXECUTION OF REST API FOR PRODUCT RATING


Step 1 - Create Database Connection for REST API Part


define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'product_review_and_rating');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Step 2 - Implement CREATE API For Product Rating

 

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/Database.php';
include_once '../class/Items.php';
$database = new Database();
$db = $database->getConnection();
$items = new Items($db);
$data = json_decode(file_get_contents("php://input"));
if(!empty($data->user_id) && !empty($data->product_id) &&
!empty($data->rating) ){
$items->user_id = $data->user_id;
$items->product_id = $data->product_id;
$items->rating = $data->rating;
if($items->create()){
http_response_code(201);
echo json_encode(array("status" => "success"));
echo json_encode(array("userMessage" => "Inserted Successfully"));
} else{
http_response_code(503);
echo json_encode(array("status" => "503"));
echo json_encode(array("userMessage" => "Unable to create item."));
}
}else{
http_response_code(400);
echo json_encode(array("status code" => "400"));
echo json_encode(array("userMessage" => "Unable to create item. Data is incomplete."));
}
?>

Step 3 - Implement READ API For Product Rating


header("Content-Type: application/json; charset=UTF-8");
include_once '../config/Database.php';
include_once '../class/Items.php';
$database = new Database();
$db = $database->getConnection();
$items = new Items($db);
$items->id = (isset($_GET['id']) && $_GET['id']) ? $_GET['id'] : '0';
$result = $items->read();
if($result->num_rows > 0){
$itemRecords=array();
$itemRecords["products"]=array();
while ($item = $result->fetch_assoc()) {
extract($item);
$itemDetails=array(
"user id" => $user_id,
"product id" => $product_id,
"rating" => $rating,
);
array_push($itemRecords["products"], $itemDetails);
}
http_response_code(200);
echo json_encode($itemRecords);
}else{
http_response_code(404);
echo json_encode(
array("message" => "No item found.")
);
}
?>

Step 4 - Implement READ AVERAGE RATING OF PARTICULAR PRODUCT API For Items


header("Content-Type: application/json; charset=UTF-8");
include_once '../config/Database.php';
include_once '../class/Items.php';
$database = new Database();
$db = $database->getConnection();
$items = new Items($db);
$items->id = (isset($_GET['id']) && $_GET['id']) ? $_GET['id'] : '0';
$result = $items->read();
if($result->num_rows > 0){
$itemRecords=array();
$itemRecords["products"]=array();
while ($item = $result->fetch_assoc()) {
extract($item);
$itemDetails=array(
"user id" => $user_id,
"product id" => $product_id,
"rating" => $rating,
);
array_push($itemRecords["products"], $itemDetails);
}
http_response_code(200);
echo json_encode($itemRecords);
}else{
http_response_code(404);
echo json_encode(
array("message" => "No item found.")
);
}
?>

Step 5 - Make SEO Friendly Request URLs of REST API (.htaccess file)


RewriteEngine On # Turn on the rewriting engine
RewriteRule ^read$ read.php [NC,L]
RewriteRule ^read/([0-9_-]*)$ read.php?id=$1 [NC,L]
RewriteRule ^create$ create.php [NC,L]
RewriteRule ^update$ update.php [NC,L]
RewriteRule ^delete$ delete.php [NC,L]

STEP-BY-STEP EXECUTION OF REST API FOR PRODUCT REVIEW


Step 1 - Create Database Connection for REST API Part


define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'product_review_and_rating');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Step 2 - Implement CREATE API For Product Review

 

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/Database.php';
include_once '../class/Items.php';
$database = new Database();
$db = $database->getConnection();
$items = new Items($db);
$data = json_decode(file_get_contents("php://input"));
if(!empty($data->user_id) && !empty($data->product_id) &&
!empty($data->heading) && !empty($data->description) ){
$items->user_id = $data->user_id;
$items->product_id = $data->product_id;
$items->heading = $data->heading;
$items->description = $data->description;
//$items->category_id = $data->category_id;
//$items->created = date('Y-m-d H:i:s');
if($items->create()){
http_response_code(201);
echo json_encode(array("status" => "success"));
echo json_encode(array("userMessage" => "Inserted Successfully"));
} else{
http_response_code(503);
echo json_encode(array("status" => "503"));
echo json_encode(array("userMessage" => "Unable to create item."));
}
}else{
http_response_code(400);
echo json_encode(array("status code" => "400"));
echo json_encode(array("userMessage" => "Unable to create item. Data is incomplete."));
}
?>

Step 3 - Implement READ API For Product Review


header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once '../config/Database.php';
include_once '../class/Items.php';
$database = new Database();
$db = $database->getConnection();
$items = new Items($db);
$items->id = (isset($_GET['id']) && $_GET['id']) ? $_GET['id'] : '0';
$result = $items->read();
if($result->num_rows > 0){
$itemRecords=array();
$itemRecords["products"]=array();
while ($item = $result->fetch_assoc()) {
extract($item);
$itemDetails=array(
"user id" => $user_id,
"product id" => $product_id,
"heading" => $heading,
"description" => $description,
);
array_push($itemRecords["products"], $itemDetails);
}
http_response_code(200);
echo json_encode($itemRecords);
}else{
http_response_code(404);
echo json_encode(
array("message" => "No item found.")
);
}
?>

Step 5 - Make SEO Friendly Request URLs of REST API (.htaccess file)


RewriteEngine On # Turn on the rewriting engine
RewriteRule ^read$ read.php [NC,L]
RewriteRule ^read/([0-9_-]*)$ read.php?id=$1 [NC,L]
RewriteRule ^create$ create.php [NC,L]
RewriteRule ^update$ update.php [NC,L]
RewriteRule ^delete$ delete.php [NC,L]

TESTING OF BOTH CREATE AND READ REST API


I have used POSTMAN API software to test my REST APIs are working correctly or not.


CREATE API  FOR PRODUCT RATING USING POSTMAN SOFTWARE



READ API FOR PRODUCT RATING USING POSTMAN SOFTWARE



READ API FOR AVERAGE PRODUCT RATING USING POSTMAN SOFTWARE



CREATE API FOR PRODUCT REVIEW USING POSTMAN SOFTWARE



READ API FOR PRODUCT REVIEW USING POSTMAN SOFTWARE



Post a Comment

0 Comments