What is an API?
API stands for Application Programming Interface. It's an interface that allows applications to communicate with each other. In the case of the web, it refers to the interface (a set of URLs that allows you to exchange data with a web application via a set of operations commonly known as CRUD - -Create, Read, Update and Delete operations by sending HTTP requests such as POST, GET, PUT and DELETE, etc.
What is REST API?
REST stands for REpresentational State Transfer". It's a set of rules that define how to exchange resources in a distributed system such as stateleness i.e the server doesn't keep any information about the previous requests which means the current request should include every information the server needs for fulfilling the desired operation. Data is usually exchanged in JSON (JavaScript Object Notation) format.
So REST API refers to the interface that allows mobile devices and web browsers (or also other web servers) to create, read, update and delete resources in the server respecting the REST rules (such as being stateless).
In order to build a web API, you need a way to store data, behind the scene, in your server's database. For this we'll use MySQL RDMS (Relational Database Management System) which is the most used database system in the PHP world.
create config/data/database.sql
CREATE DATABASE mydb;
use mydb;
CREATE TABLE `Product` (
`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`sku` varchar(255),
`barcode` varchar(255),
`name` varchar(100),
`price` float,
`unit` varchar(20),
`quantity` float,
`minquantity` float,
`createdAt` datetime NOT NULL,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`familyid` int(11) NOT NULL,
`locationid` int(11) NOT NULL
);
CREATE TABLE `Family` (
`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`reference` varchar(50),
`name` varchar(100),
`createdAt` datetime NOT NULL,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Now we need to create a file config/install.php
include_once './dbclass.php';
try
{
$dbclass = new DBClass();
$connection = $dbclass.getConnection();
$sql = file_get_contents("data/database.sql");
$connection->exec($sql);
echo "Database and tables created successfully!";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Connecting to A MySQL Database in PHP
Inside the config folder add a dbclass.php file
<?php
class DBClass {
private $host = "localhost";
private $username = "root";
private $password = "<YOUR_DB_PASSWORD>";
private $database = "<YOUR_DB_NAME>";
public $connection;
// get the database connection
public function getConnection(){
$this->connection = null;
try{
$this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);
$this->connection->exec("set names utf8");
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
return $this->connection;
}
}
?>
Next, we'll create the PHP classes that encapsulate the entities (or database tables). Each class will contain a hard-coded string storing the name of the corresponding SQL table, a member variable that will be holding an instance of the Connection class which will be passed via the class constructor, and other fields mapping to the table columns. Each entity class will also encapsulate the CRUD operations needed for creating, reading, updating, and deleting the corresponding table rows.
The PHP Product Class
<?php
class Product{
// Connection instance
private $connection;
// table name
private $table_name = "Product";
// table columns
public $id;
public $sku;
public $barcode;
public $name;
public $price;
public $unit;
public $quantity;
public $minquantity;
public $createdAt;
public $updatedAt;
public $family_id;
public $location_id;
public function __construct($connection){
$this->connection = $connection;
}
//C
public function create(){
}
//R
public function read(){
$query = "SELECT c.name as family_name, p.id, p.sku, p.barcode, p.name, p.price, p.unit, p.quantity , p.minquantity, p.createdAt, p.updatedAt FROM" . $this->table_name . " p LEFT JOIN Family c ON p.family_id = c.id ORDER BY p.createdAt DESC";
$stmt = $this->connection->prepare($query);
$stmt->execute();
return $stmt;
}
//U
public function update(){}
//D
public function delete(){}
}
The PHP Transaction Class
<?php
class Transaction{
// Connection instance
private $connection;
// table name
private $table_name = "Transaction";
// table columns
public $id;
public $comment;
public $price;
public $quantity;
public $reason;
public $createdAt;
public $updatedAt;
public $product_id;
public function __construct($connection){
$this->connection = $connection;
}
//C
public function create(){}
//R
public function read(){}
//U
public function update(){}
//D
public function delete(){}
}
The PHP Family Class
<?php
class Family{
// Connection instance
private $connection;
// table name
private $table_name = "Family";
// table columns
public $id;
public $reference;
public $name;
public $createdAt;
public $updatedAt;
public function __construct($connection){
$this->connection = $connection;
}
//C
public function create(){}
//R
public function read(){}
//U
public function update(){}
//D
public function delete(){}
}
The PHP Location Class
<?php
class Location{
// Connection instance
private $connection;
// table name
private $table_name = "Location";
// table columns
public $id;
public $reference;
public $description;
public $createdAt;
public $updatedAt;
public function __construct($connection){
$this->connection = $connection;
}
//C
public function create(){}
//R
public function read(){}
//U
public function update(){}
//D
public function delete(){}
}
HTTP GET API Example: Implementing products/read.php
<?
header("Content-Type: application/json; charset=UTF-8");
include_once '../config/dbclass.php';
include_once '../entities/product.php';
$dbclass = new DBClass();
$connection = $dbclass->getConnection();
$product = new Product($connection);
$stmt = $product->read();
$count = $stmt->rowCount();
if($count > 0){
$products = array();
$products["body"] = array();
$products["count"] = $count;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$p = array(
"id" => $id,
"sku" => $sku,
"barcode" => $barcode,
"name" => $name,
"price" => $price,
"unit" => $unit,
"quantity" => $quantity,
"minquantity" => $minquantity,
"createdAt" => $createdAt,
"createdAt" => $createdAt,
"updatedAt" => $updatedAt,
"family_id" => $family_id,
"location_id" => $location_id
);
array_push($products["body"], $p);
}
echo json_encode($products);
}
else {
echo json_encode(
array("body" => array(), "count" => 0);
);
}
?>
HTTP POST API Example: Implementing product/create.php
<?php
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/dbclass.php';
include_once '../entities/product.php';
$dbclass = new DBClass();
$connection = $dbclass->getConnection();
$product = new Product($connection);
$data = json_decode(file_get_contents("php://input"));
$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');
if($product->create()){
echo '{';
echo '"message": "Product was created."';
echo '}';
}
else{
echo '{';
echo '"message": "Unable to create product."';
echo '}';
}
?>