Project Description ( PHP )

Project : In this project we will learn how to create simple REST API in php with all crud operation .

You must have basic knowledge in php & php oops and mysql database (phpmyadmin), queries.

  • How to use all headers for api access.
  • Create API URL to insert data.
  • Fetch API to fetch all data.
  • Fetch API to fetch single data by using GET method.
  • Fetch API to fetch single data by using POST method.
  • Delete API to delete data by using GET method.
  • Delete API to delete data by using POST method.
  • Test all API URL on postman.
Imaportant things to keep rememeber about headers for REST API in php,There are many headers available for different access, check below. You can read more about headers by searching in google.

HEADERS (Must be declare on top of file)

                            
                              header("Access-Control-Allow-Origin: *");
                              header("Content-Type: application/json; charset:UTF-8");
                              header("Access-Control-Allow-Methods: POST");// POST OR GET OR PUT 
                            
                          

Create database and connect with database

Go to phpmAdmin, create database and table
PHP
myproject/config/database.php
database.php
                            
                                class Database{

                                  private $hostname;
                                  private $username;
                                  private $password;
                                  private $dbname;

                                  private $conn;

                                  public function connect(){
                                    // varialiable initialization;
                                    $this->hostname="localhost";
                                    $this->username="root";
                                    $this->password="";
                                    $this->dbname="phpapi";

                                    $this->conn = new mysqli($this->hostname,$this->username,$this->password,$this->dbname);

                                    if($this->conn->connect_error){
                                      print_r($this->conn->connect_error);
                                      exit();
                                    }else{
                                      // echo "Connected....!!!";
                                      return $this->conn;
                                    }
                                  }
                                }

                                // $db = new Database();
                                // $db->connect();
                            
                          

Classes

Create client class in classes folder

classes/Client.php
Client.php
                              
                                class Client{
                                    public  $name;
                                    public  $email;
                                    public  $mobile;
                                    public  $cid;
                                    private $conn;
                                    private $table_client;

                                    public function  __construct($db){
                                      $this->conn = $db;
                                      $this->table_client = "clients";
                                    }
                                    // check client if already exists in database
                                    public function check_email(){
                                      $query ="SELECT * FROM ".$this->table_client." WHERE email=?";
                                      $obj = $this->conn->prepare($query);
                                      $obj->bind_param("s",$this->email);
                                      if($obj->execute()){
                                        $data = $obj->get_result();
                                        return $data->fetch_assoc();
                                      }else{
                                        return [];
                                      }
                                    }
                                    // add client in database client table
                                    public function create_client(){
                                      $query ="INSERT INTO ".$this->table_client."  SET name=?, email=?, mobile=? ";
                                      $obj = $this->conn->prepare($query);
                                      $this->name = htmlspecialchars(strip_tags($this->name));
                                      $this->email = htmlspecialchars(strip_tags($this->email));
                                      $this->mobile = htmlspecialchars(strip_tags($this->mobile));
                                      $obj->bind_param("sss",$this->name,$this->email,$this->mobile);
                                      if($obj->execute()){
                                        return true;
                                      }else{
                                        return false;
                                      }
                                    }

                                    //read all the data
                                    public function get_all_clients(){
                                      $query = "SELECT * FROM ".$this->table_client;
                                      //prepare the the sql
                                      $obj = $this->conn->prepare($query);
                                      if($obj->execute()){
                                        return $obj->get_result();
                                      }else{
                                        return false;
                                      }
                                    }
                                    // fetch single client
                                    public function fetch_single_data(){
                                      $query ="SELECT * FROM ".$this->table_client." WHERE cid=?";
                                      $obj = $this->conn->prepare($query);
                                      $obj->bind_param('i', $this->cid);
                                      if($obj->execute()){
                                        $data = $obj->get_result();
                                        return $data->fetch_assoc();
                                      }else{
                                        return false;
                                      }
                                    }
                                    // update client information
                                    public function update_client(){
                                      $query ="UPDATE ".$this->table_client."  SET name=?, email=?, mobile=? WHERE cid=? ";
                                      $obj = $this->conn->prepare($query);
                                      $this->name = htmlspecialchars(strip_tags($this->name));
                                      $this->email = htmlspecialchars(strip_tags($this->email));
                                      $this->mobile = htmlspecialchars(strip_tags($this->mobile));
                                      $this->cid = htmlspecialchars(strip_tags($this->cid));
                                      $obj->bind_param("sssi",$this->name,$this->email,$this->mobile, $this->cid);
                                      if($obj->execute()){
                                        return true;
                                      }else{
                                        return false;
                                      }
                                    }
                                    //delete client
                                    public function delete_client(){
                                      $query ="DELETE FROM ".$this->table_client." WHERE cid=? ";
                                      $obj = $this->conn->prepare($query);
                                      $this->cid = htmlspecialchars(strip_tags($this->cid));
                                      $obj->bind_param("i", $this->cid);
                                      if($obj->execute()){
                                        return true;
                                      }else{
                                        return false;
                                      }
                                    }
                                  }
                              
                          

api (Create API URL)

Create all API URL files in api folder

myproject/api/create.php
create.php
                            
                              ini_set("display_error", 1);

                              header("Access-Control-Allow-Origin: *");
                              header("Content-Type: application/json; charset:UTF-8");
                              header("Access-Control-Allow-Methods: POST");

                              include_once('../config/database.php');
                              include_once('../classes/Client.php');
                              //objects
                              $db = new Database();
                              $connection = $db->connect();
                              $obj = new Client($connection);

                              if($_SERVER['REQUEST_METHOD']=='POST'){
                                $data = json_decode(file_get_contents("php://input")); //from postman
                                if(!empty($data->name) && !empty($data->email) && !empty($data->mobile)){
                                  //dynamic
                                  $obj->name = $data->name;
                                  $obj->email = $data->email;
                                  $obj->mobile = $data->mobile;
                                  $email_data = $obj->check_email();
                                  if(!empty($email_data)){
                                    http_response_code(500);
                                    echo json_encode([
                                      "status"=>0,
                                      "message"=>"Client already exist, try another"
                                    ]);
                                  }else{
                                    if($obj->create_client()){
                                      http_response_code(200); // means ok
                                      echo json_encode([
                                        "status"=> 1,
                                        "message"=> "Client has been created successfully"
                                      ]);
                                    }else{
                                      http_response_code(500); //means internal server error
                                      echo json_encode([
                                        "status"=> 0,
                                        "message"=> "Failed to insert data"
                                      ]);
                                    }
                                  }
                                }else{
                                    http_response_code(404); //404 means page not found
                                    echo json_encode([
                                      "status"=> 0,
                                      "message"=> "All the inputs are required"
                                    ]);
                                  }
                              }else{
                                http_response_code(503); //means internal server error
                                echo json_encode([
                                  "status"=> 0,
                                  "message"=> "Access denied"
                                ]);
                              }
                            
                          

Test create API in postman to create client

Postman : Postman API Platform, Postman is an application used for API testing, click on download
PHP

Fetch API URL

myproject/api/list.php
list.php
                            
                                ini_set("display_error", 1);

                                header("Access-Control-Allow-Origin: *");
                                header("Content-Type: application/json; charset:UTF-8");
                                header("Access-Control-Allow-Methods: GET");

                                include_once('../config/database.php');
                                include_once('../classes/Client.php');

                                //objects
                                $db = new Database();
                                $connection = $db->connect();
                                $obj = new Client($connection);

                                if($_SERVER['REQUEST_METHOD']=='GET'){
                                  $clients = $obj->get_all_clients();
                                  if($clients->num_rows >0){
                                    $client_data = [];
                                    while($row = $clients->fetch_assoc()){
                                      $client_data[] = [
                                        'cid'   =>$row['cid'],
                                        'name'  =>$row['name'],
                                        'email' =>$row['email'],
                                        'mobile'=>$row['mobile'],
                                        'status'=>$row['status'],
                                        'created_at'=>$row['created_at']
                                      ];
                                    }
                                    http_response_code(200);
                                    echo json_encode([
                                      'status'=>1,
                                      'message'=>$client_data 
                                    ]);
                                  }else{
                                    http_response_code(404);
                                    echo json_encode([
                                      'status'=>0,
                                      'message'=>'No client found',
                                    ]);
                                  }
                                }else{
                                  http_response_code(503); //means internal server error
                                  echo json_encode([
                                    "status"=> 0,
                                    "message"=> "Access denied"
                                  ]);
                                }
                            
                          

Test list API in postman to fetch all data

PHP
Fetch Single data by GET method
myproject/api/single-data-by-get-method.php
single-data-by-get-method.php
                            
                              ini_set("display_error", 1);

                              header("Access-Control-Allow-Origin: *");
                              header("Content-Type: application/json; charset:UTF-8");
                              header("Access-Control-Allow-Methods: GET");

                              include_once('../config/database.php');
                              include_once('../classes/Client.php');

                              //objects
                              $db = new Database();
                              $connection = $db->connect();
                              $obj = new Client($connection);
                              if($_SERVER['REQUEST_METHOD']==='GET'){
                                   $client_id = isset($_GET['cid']) ? intval($_GET['cid']) : "";
                                   if(!empty($client_id)){
                                    $obj->cid = $client_id;
                                    $client_data = $obj->fetch_single_data();
                                    if(!empty($client_data)){
                                      http_response_code(200); //means internal server error
                                    echo json_encode([
                                      "status"=> 1,
                                      "message"=> $client_data,
                                    ]);
                                    }else{
                                      http_response_code(404);
                                    echo json_encode([
                                      'status'=>0,
                                      'message'=>'Client not  found',
                                    ]);
                                    }
                                }else{
                                  http_response_code(404);
                                  echo json_encode([
                                    'status'=>0,
                                    'message'=>'Client does not exist',
                                  ]);
                                }

                              }else{
                                http_response_code(503); //means internal server error
                                echo json_encode([
                                  "status"=> 0,
                                  "message"=> "Access denied"
                                ]);
                              }
                            
                          

Test API in postman to fetch single data by GET method

Pass the cid in url (which is query staring) => ?cid=1 and use GET method

PHP
Fetch Single data by POST method
myproject/api/single-data-by-post-method.php
single-data-by-post-method.php
                            
                              ini_set("display_error", 1);

                              header("Access-Control-Allow-Origin: *");
                              header("Content-Type: application/json; charset:UTF-8");
                              header("Access-Control-Allow-Methods: POST");

                              include_once('../config/database.php');
                              include_once('../classes/Client.php');

                              //objects
                              $db = new Database();
                              $connection = $db->connect();
                              $obj = new Client($connection);

                              if($_SERVER['REQUEST_METHOD']==='POST'){
                                   $data = json_decode(file_get_contents("php://input"));
                                   if(!empty($data->cid)){
                                    $obj->cid = $data->cid;
                                    $client_data = $obj->fetch_single_data();
                                    if(!empty($client_data)){
                                      http_response_code(200); //means internal server error
                                    echo json_encode([
                                      "status"=> 1,
                                      "message"=> $client_data,
                                    ]);
                                    }else{
                                      http_response_code(404);
                                    echo json_encode([
                                      'status'=>0,
                                      'message'=>'User not  found',
                                    ]);
                                    }
                                }else{
                                  http_response_code(404);
                                  echo json_encode([
                                    'status'=>0,
                                    'message'=>'User does not exist',
                                  ]);
                                }

                              }else{
                                http_response_code(503); //means internal server error
                                echo json_encode([
                                  "status"=> 0,
                                  "message"=> "Access denied"
                                ]);
                              }
                            
                          

Test API in postman to fetch single data by POST method

Pass the input cid in body and use POST method (exmaple is given in picture)

PHP
Update data by POST method
myproject/api/update.php
update.php
                            
                              ini_set("display_error", 1);
                              header("Access-Control-Allow-Origin: *");
                              header("Content-Type: application/json; charset:UTF-8");
                              header("Access-Control-Allow-Methods: POST");


                              include_once('../config/database.php');
                              include_once('../classes/Client.php');
                              //objects
                              $db = new Database();
                              $connection = $db->connect();
                              $obj = new Client($connection);
                              if($_SERVER['REQUEST_METHOD']=='POST'){
                                $data = json_decode(file_get_contents("php://input")); //from postman
                                if(!empty($data->name) && !empty($data->email) && !empty($data->mobile)){
                                  //dynamic
                                  $obj->name = $data->name;
                                  $obj->email = $data->email;
                                  $obj->mobile = $data->mobile;
                                  $obj->cid = $data->cid;

                                  if($obj->update_client()){
                                    http_response_code(200); // means ok
                                    echo json_encode([
                                      "status"=> 1,
                                      "message"=> "Clinet has been updated successfully"
                                    ]);
                                  }else{
                                    http_response_code(500); //means internal server error
                                    echo json_encode([
                                      "status"=> 0,
                                      "message"=> "Failed to update data"
                                    ]);
                                  }
                                }else{
                                  http_response_code(404); //404 means page not found
                                  echo json_encode([
                                    "status"=> 0,
                                    "message"=> "All the inputs are required"
                                  ]);
                                }
                              }else{
                                http_response_code(503); //means internal server error
                                echo json_encode([
                                  "status"=> 0,
                                  "message"=> "Access denied"
                                ]);
                              }
                            
                          

Test API in postman to update data by POST method

Pass the input data in body and use POST method (exmaple is given in picture)

PHP
Delete data by GET method
myproject/api/delete-by-get-method.php
delete-by-get-method.php
                            
                              ini_set("display_error", 1);

                              header("Access-Control-Allow-Origin: *");
                              header("Content-Type: application/json; charset:UTF-8");
                              header("Access-Control-Allow-Methods: GET");
                              include_once('../config/database.php');
                              include_once('../classes/Client.php');
                              //objects
                              $db = new Database();
                              $connection = $db->connect();
                              $obj = new Client($connection);

                              if($_SERVER['REQUEST_METHOD']==='GET'){
                                $cid = isset($_GET['cid']) ? intval($_GET['cid']) : "";
                                if(!empty($cid)){
                                  $obj->cid = $cid;
                                  if($obj->delete_client()){
                                    http_response_code(200); // means ok
                                    echo json_encode([
                                      "status" => 1,
                                      "message"=> "Client has been deleted successfully"
                                    ]);
                                  }else{
                                    http_response_code(500); // means internal server error
                                    echo json_encode([
                                      "status" => 0,
                                      "message"=> "Failed to delete data"
                                    ]);
                                  }
                                }else{
                                  http_response_code(404); // 404 means page not found
                                  echo json_encode([
                                    "status" => 0,
                                    "message"=> "The Client not found"
                                  ]);
                                }
                              }else{
                                http_response_code(503); //means internal server error
                                echo json_encode([
                                  "status"=> 0,
                                  "message"=> "Access denied"
                                ]);
                              }
                            
                          

Test API in postman to delete data by GET method

Pass the cid in URL => ?cid=1 and use GET method

PHP

Delete data by POST method
myproject/api/delete-by-post-method.php
delete-by-post-method.php
                            
                              ini_set("display_error", 1);

                              header("Access-Control-Allow-Origin: *");
                              header("Content-Type: application/json; charset:UTF-8");
                              header("Access-Control-Allow-Methods: POST");
                              include_once('../config/database.php');
                              include_once('../classes/Client.php');
                              //objects
                              $db = new Database();
                              $connection = $db->connect();
                              $obj = new Client($connection);

                              if($_SERVER['REQUEST_METHOD']=='POST'){
                                $data = json_decode(file_get_contents("php://input")); 
                                if(!empty($data->cid)){
                                  $obj->cid = $data->cid;
                                  if($obj->delete_client()){
                                    http_response_code(200); // means ok
                                    echo json_encode([
                                      "status"=> 1,
                                      "message"=> "User has been deleted successfully"
                                    ]);
                                  }else{
                                    http_response_code(500); //means internal server error
                                    echo json_encode([
                                      "status"=> 0,
                                      "message"=> "Failed to delete data"
                                    ]);
                                  }
                                }else{
                                  http_response_code(404); //404 means page not found
                                  echo json_encode([
                                    "status"=> 0,
                                    "message"=> "The user not found"
                                  ]);
                                }
                              }else{
                                http_response_code(503); //means internal server error
                                echo json_encode([
                                  "status"=> 0,
                                  "message"=> "Access denied"
                                ]);
                              }
                            
                          

Test API in postman to delete data by POST method

Pass the unput cid in body use method (exmaple is given in picture)

PHP