HOW TO CREATE SIMPLE RESTful API IN PHP
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
class
items
config
Database
include
config
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
`id` int(11) NOT NULL AUTO INCREMENT,
`name` varchar(256) NOT NULL,
`description` text NOT NULL,
`price` int(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Step 2 - Insert Data For Demo In MYSQL Database Table
(1, 'ProductA', 'sample product', 100.1),
(2, 'ProductB', 'sample product', 200.1),
(3, 'Usha Sewing Machine', 'its best machine', 90000),
(4, 'Usha Sewing Machine', 'its best machine', 90000),
(5, 'Rishabh Sewing Machine', 'its best machine', 90000),
(6, 'Rishabh Sewing Machine', 'its best machine', 90000),
(7, 'Jahanvi Di Product API Project', 'its best project', 525);
Step 3 - Create Database Connection for Php Project
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'svachaalanproject');
$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
Step 1 - Create Database Connection for REST API Part
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'svachaalanproject');
$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 Items
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->product_name) && !empty($data->product_description) &&
!empty($data->product_price) ){
$items->product_name = $data->product_name;
$items->product_description = $data->product_description;
$items->product_price = $data->product_price;
//$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 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(
"id" => $id,
"product_name" => $product_name,
"product_description" => $product_description,
"product_price" => $product_price,
);
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 - Make SEO Friendly Request URLs of REST API
RewriteRule ^read$ read.php [NC,L]
RewriteRule ^read/([0-9_-]*)$ read.php?id=$1 [NC,L]
RewriteRule ^create$ create.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.
0 Comments