If you are looking to set up Rest Api Using Php here are steps to follow for How To Setup Simple REST API Using PHP?
Table of Contents
Overview:
1. What is REST API?
2. How To INSERT Data Using REST API?
3. How To READ Data Using REST API?
4. How To UPDATE Data Using REST API?
5. How To DELETE Data Using REST API?
1. What is REST API using PHP?
GUYS, we are learning REST API, To define “REST API”, We Have To Know What is “REST” and What is “API” First.
let’s Get Started:)
Guys, “API” What is API?
API stands for “Application Programming Interface”.
API is just a piece of program or a set of rules that provides a way of communication from one software application to another software application.
for example: when we use some app or website to book our tickets. we take the example of PAYTM.when to explore Paytm to book our tickets, we see ‘how many tickets are left?
and also ‘what seat is booked’? or ‘what seat is still blank’?
in the background Paytm fetch data through API and displays it in our app.
Then REST Stands for “REPRESENTATIONAL STATE TRANSFER”. REST API Using PHP is a concept of managing or transferring Information and Data over the internet. REST is Referred to as Resource. REST is usually represented by JSON. REST has a lot of concepts inside of it. I explain some basic operations(INSERT, READ, UPDATE & DELETE) that are performed by REST API. if you want to learn more, you can check the Documentation: https://developer.wordpress.com/docs/api/
OPERATIONS:
Before start performing the operations, we need to set up a database. so get ready to set up a database.
SETUP THE DATABASE:
Using PhpMyAdmin, create a new “restapi_db” database. Yes, “restapi_db” is the database name. After that, run the following SQL queries to create new tables with sample data.
Create Products Table:
[php]
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`description` text NOT NULL,
`price` decimal(10,0) NOT NULL,
`category_id` int(11) NOT NULL,
`created` datetime NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=65 ;
[/php]
Insert Data For Products Table:
[php]
INSERT INTO `products` (`id`, `name`, `description`, `price`, `category_id`, `created`, `modified`) VALUES
(1, ‘LG P880 4X HD’, ‘My first awesome phone!’, ‘336’, 3, ‘2014-06-01 01:12:26’, ‘2014-05-31 17:12:26’),
(2, ‘Google Nexus 4’, ‘The most awesome phone of 2013!’, ‘299’, 2, ‘2014-06-01 01:12:26’, ‘2014-05-31 17:12:26’),
(3, ‘Samsung Galaxy S4’, ‘How about no?’, ‘600’, 3, ‘2014-06-01 01:12:26’, ‘2014-05-31 17:12:26’),
(4, ‘Bench Shirt’, ‘The best shirt!’, ’29’, 1, ‘2014-06-01 01:12:26’, ‘2014-05-31 02:12:21’),
(5, ‘Lenovo Laptop’, ‘My business partner.’, ‘399’, 2, ‘2014-06-01 01:13:45’, ‘2014-05-31 02:13:39’),
(6, ‘Samsung Galaxy Tab 10.1’, ‘Good tablet.’, ‘259’, 2, ‘2014-06-01 01:14:13’, ‘2014-05-31 02:14:08’),
(7, ‘Spalding Watch’, ‘My sports watch.’, ‘199’, 1, ‘2014-06-01 01:18:36’, ‘2014-05-31 02:18:31’),
(8, ‘Sony Smart Watch’, ‘The coolest smart watch!’, ‘300’, 2, ‘2014-06-06 17:10:01’, ‘2014-06-05 18:09:51’),
(9, ‘Huawei Y300’, ‘For testing purposes.’, ‘100’, 2, ‘2014-06-06 17:11:04’, ‘2014-06-05 18:10:54’),
(10, ‘Rolex Watch’, ‘Luxury watch.’, ‘25000’, 1, ‘2016-01-11 15:46:02’, ‘2016-01-11 14:46:02’);
[/php]
Connect to database:
Create “config” folder. Open that folder and create “database.php” file. Put the following code inside it.
[php]
<?php class Database{ // specify your own database credentials private $host = “localhost”; private $db_name = “api_db”; private $username = “root”; private $password = “”; public $conn; // get the database connection public function getConnection(){ $this->conn = null; try{ $this->conn = new PDO(“mysql:host=” . $this->host . “;dbname=” . $this->db_name, $this->username, $this->password); $this->conn->exec(“set names utf8”); }catch(PDOException $exception){ echo “Connection error: ” . $exception->getMessage(); } return $this->conn; } } ?>
[/php]
2. How To INSERT Data Using REST API?
Create insert.php file:
Open “product” folder. Create a new “insert.php” file. Open that file and put the following code inside it.
[php]
<?php
// required headers
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”);
// get database connection
include_once ‘../config/database.php’;
// instantiate product object
include_once ‘../objects/product.php’;
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
// get posted data
$data = json_decode(file_get_contents(“php://input”));
// set product property values
$product->name = $data->name;
$product->price = $data->price;
$product->description = $data->description;
$product->category_id = $data->category_id;
$product->created = date(‘Y-m-d H:i:s’);
// insert the product
if($product->insert()){
echo ‘{‘;
echo ‘”message”: “Product was insrted.”‘;
echo ‘}’;
}
// if unable to insert the product, tell the user
else{
echo ‘{‘;
echo ‘”message”: “Unable to insert product.”‘;
echo ‘}’;
}
?>
[/php]
Product insert() method:
Open the “objects” folder. Open the “product.php” file. The previous section will not work without the following code inside the Product (objects/product.php) class.
Add the following method inside the “Product” class. To make sure you added it correctly, but the code before the last closing curly brace.
[php]
// insert product
function insert(){
// query to insert record
$query = “INSERT INTO
” . $this->table_name . ”
SET
name=:name, price=:price, description=:description, category_id=:category_id, created=:created”;
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->name=htmlspecialchars(strip_tags($this->name));
$this->price=htmlspecialchars(strip_tags($this->price));
$this->description=htmlspecialchars(strip_tags($this->description));
$this->category_id=htmlspecialchars(strip_tags($this->category_id));
$this->created=htmlspecialchars(strip_tags($this->created));
// bind values
$stmt->bindParam(“:name”, $this->name);
$stmt->bindParam(“:price”, $this->price);
$stmt->bindParam(“:description”, $this->description);
$stmt->bindParam(“:category_id”, $this->category_id);
$stmt->bindParam(“:created”, $this->created);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
[/php]
3. How To READ Data Using REST API?
One more step which make process easy for How To Setup Simple REST API Using PHP..
Create “objects” folder. Open that folder and create “product.php” file. Put the following code inside it.
[php]
<?php
class Product{
// database connection and table name
private $conn;
private $table_name = “products”;
// object properties
public $id;
public $name;
public $description;
public $price;
public $category_id;
public $category_name;
public $created;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
}
[/php]
Create “read.php” file:
Create “product” folder. Open that folder and create “read.php” file. Put the following code inside it.
[php]
<?php
// required headers
header(“Access-Control-Allow-Origin: *”);
header(“Content-Type: application/json; charset=UTF-8”);
// include database and object files
include_once ‘../config/database.php’;
include_once ‘../objects/product.php’;
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
// initialize object
$product = new Product($db);
// query products
$stmt = $product->read();
$num = $stmt->rowCount();
// check if more than 0 record found
if($num>0){
// products array
$products_arr=array();
$products_arr[“records”]=array();
// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// extract row
// this will make $row[‘name’] to
// just $name only
extract($row);
$product_item=array(
“id” => $id,
“name” => $name,
“description” => html_entity_decode($description),
“price” => $price,
“category_id” => $category_id,
“category_name” => $category_name
);
array_push($products_arr[“records”], $product_item);
}
echo json_encode($products_arr);
}
else{
echo json_encode(
array(“message” => “No products found.”)
);
}
?>
[/php]
Add Product “read()” method:
Open the “objects” folder. Open the “product.php” file. The code in the previous section will not work without the following code in the “product.php” file.
Add the following method inside the “Product” class. To make sure you added it correctly, but the code before the last closing curly brace.
[php]
// read products
function read(){
// select all query
$query = “SELECT
c.name as category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
FROM
” . $this->table_name . ” p
LEFT JOIN
categories c
ON p.category_id = c.id
ORDER BY
p.created DESC”;
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
return $stmt;
}
[/php]
Output:
[sourcecode language=”plain”]
If you develop on localhost and will run the read.php file using this URL: http://localhost/api/product/read.php
you can test API by a “POSTMAN” tool, yes “POSTMAN” is the name of the tool you can launch this tool in as a google chrome extension by this link: https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
[/sourcecode]
Notice: Extension works only in chrome browser.
READ ONE PRODUCT:
Create read_one.php file
Open “product” folder. Create new “read_one.php” file. Open that file and put the following code.
[php]
<?php
header(“Access-Control-Allow-Origin: *”);
header(“Access-Control-Allow-Headers: access”);
header(“Access-Control-Allow-Methods: GET”);
header(“Access-Control-Allow-Credentials: true”);
header(‘Content-Type: application/json’);
// include database and object files
include_once ‘../config/database.php’;
include_once ‘../objects/product.php’;
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$product = new Product($db);
// set ID property of product to be edited
$product->id = isset($_GET[‘id’]) ? $_GET[‘id’] : die();
// read the details of product to be edited
$product->readOne();
// create array
$product_arr = array(
“id” => $product->id,
“name” => $product->name,
“description” => $product->description,
“price” => $product->price,
“category_id” => $product->category_id,
“category_name” => $product->category_name
);
// make it json format
print_r(json_encode($product_arr));
?>
[/php]
Product readOne() method:
Open the “objects” folder. Open the “product.php” file. The previous section will not work without the following code inside the Product class.
Add the following method inside the “Product” class. To make sure you added it correctly, but the code before the last closing curly brace.
[php]
// used when filling up the update product form
function readOne(){
// query to read single record
$query = “SELECT
c.name as category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
FROM
” . $this->table_name . ” p
LEFT JOIN
categories c
ON p.category_id = c.id
WHERE
p.id = ?
LIMIT
0,1″;
// prepare query statement
$stmt = $this->conn->prepare( $query );
// bind id of product to be updated
$stmt->bindParam(1, $this->id);
// execute query
$stmt->execute();
// get retrieved row
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// set values to object properties
$this->name = $row[‘name’];
$this->price = $row[‘price’];
$this->description = $row[‘description’];
$this->category_id = $row[‘category_id’];
$this->category_name = $row[‘category_name’];
}
[/php]
Output:
[sourcecode language=”plain”]
If you develop on localhost and will run the read_one.php file using this URL: http://localhost/api/product/read_one.php?id=1
As you can see in the URL above, an ID parameter value (id=1) has to be passed.
you can test API by a “POSTMAN” tool, yes “POSTMAN” is the name of the tool you can launch this tool in as a google chrome extension by this link: https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
[/sourcecode]
Notice: Extension works only in chrome browser.
4. How To UPDATE Data Using REST API?
Create “update.php” file:
Open “product” folder. Create new “update.php” file. Open that file and put the following code inside it.
[php]
<?php
// required headers
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 database and object files
include_once ‘../config/database.php’;
include_once ‘../objects/product.php’;
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$product = new Product($db);
// get id of product to be edited
$data = json_decode(file_get_contents(“php://input”));
// set ID property of product to be edited
$product->id = $data->id;
// set product property values
$product->name = $data->name;
$product->price = $data->price;
$product->description = $data->description;
$product->category_id = $data->category_id;
// update the product
if($product->update()){
echo ‘{‘;
echo ‘”message”: “Product was updated.”‘;
echo ‘}’;
}
// if unable to update the product, tell the user
else{
echo ‘{‘;
echo ‘”message”: “Unable to update product.”‘;
echo ‘}’;
}
?>
[/php]
Product update() method
Open the “objects” folder. Open the “product.php” file. The previous section will not work without the following code inside the Product class.
Add the following method inside the “Product” class. To make sure you added it correctly, but the code before the last closing curly brace.
[php]
// update the product
function update(){
// update query
$query = “UPDATE
” . $this->table_name . ”
SET
name = :name,
price = :price,
description = :description,
category_id = :category_id
WHERE
id = :id”;
// prepare query statement
$stmt = $this->conn->prepare($query);
// sanitize
$this->name=htmlspecialchars(strip_tags($this->name));
$this->price=htmlspecialchars(strip_tags($this->price));
$this->description=htmlspecialchars(strip_tags($this->description));
$this->category_id=htmlspecialchars(strip_tags($this->category_id));
$this->id=htmlspecialchars(strip_tags($this->id));
// bind new values
$stmt->bindParam(‘:name’, $this->name);
$stmt->bindParam(‘:price’, $this->price);
$stmt->bindParam(‘:description’, $this->description);
$stmt->bindParam(‘:category_id’, $this->category_id);
$stmt->bindParam(‘:id’, $this->id);
// execute the query
if($stmt->execute()){
return true;
}
return false;
}
[/php]
5. How To DELETE Data Using REST API Using PHP?
Create “delete.php” file:
Open “product” folder. Create new “delete.php” file. Open that file and put the following code inside it.
[php]
<?php
// required headers
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 database and object file
include_once ‘../config/database.php’;
include_once ‘../objects/product.php’;
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$product = new Product($db);
// get product id
$data = json_decode(file_get_contents(“php://input”));
// set product id to be deleted
$product->id = $data->id;
// delete the product
if($product->delete()){
echo ‘{‘;
echo ‘”message”: “Product was deleted.”‘;
echo ‘}’;
}
// if unable to delete the product
else{
echo ‘{‘;
echo ‘”message”: “Unable to delete object.”‘;
echo ‘}’;
}
?>
[/php]
Product delete() method:
Open the “objects” folder. Open the “product.php” file. The previous section will not work without the following code inside the Product class.
Add the following method inside the “Product” class. To make sure you added it correctly, but the code before the last closing curly brace.
[php]
// delete the product
function delete(){
// delete query
$query = “DELETE FROM ” . $this->?table_name . ” WHERE id = ?”;
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->id=htmlspecialchars(strip_tags($this->id));
// bind id of record to delete
$stmt->bindParam(1, $this->id);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
[/php]
If you have a friend or know someone who needs this PHP REST API Tutorial, please share this page with them! I know you will help them a lot by doing it. Please follow all steps of How To Setup Simple REST API Using PHP, it will guide you to complete the process.