PHP Classes

PHP CRUD REST API Server: REST API server with MySQLi based CRUD operations

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
StarStarStarStar 67%Total: 979 This week: 1All time: 3,713 This week: 34Up
Version License PHP version Categories
rest-api-with-mysqli 1.1Freeware5PHP 5, Databases, Web services
Collaborate with this project 

Author

Description

This class can be used to implement a REST API server with MySQLi based CRUD operations.

It provides a base class that can connect to a MySQL database server using MySQLi and execute basic CRUD operations like creating, retrieving, updating and deleting records from a given table.

The REST server class itself extends the base CRUD class and processes requests looking for the requested API function. It dispatches the request if the function exists, or return a 404 response if it does not exist.

The REST class can also retrieve the request parameter data for HTTP GET, POST, PUT and DELETE methods, as well process the API call response setting the appropriate headers and HTTP status.

Applications implementing the API just need to extend the REST server class and implement the supported API calls as class methods.

A demonstration API class is provided to show how to implement a API to manage users with records stored in a database.

Innovation Award
PHP Programming Innovation award nominee
April 2016
Number 9
Nowadays, many sites provide an API, especially when they have a mobile application that needs to store and retrieve information from the site.

Many APIs provide function calls that execute CRUD operations (Create, Retrieve, Update and Delete) with data stored in a database.

This PHP package provides a solution to simplify all those goals. It provides means to easily create a REST API with functions that map to class methods.

At the same time it provide means to implement CRUD operations with a MySQL database.

The demonstration API provided with the package shows how you can easily implement an API to manipulate user records stored in a MySQL database.

Manuel Lemos
Picture of Bharat Parmar
  Performance   Level  
Name: Bharat Parmar <contact>
Classes: 11 packages by
Country: India India
Age: 33
All time rank: 51631 in India India
Week rank: 44 Up5 in India India Up
Innovation award
Innovation award
Nominee: 3x

Recommendations

What is the best PHP api creation class?
i need to create api to be executed in multiple devices

Example

<?php
   
require_once("Rest.inc.php");
   
    class
API extends REST {
        public
$data = "";
        public function
__construct(){
           
parent::__construct(); // Init parent contructor
       
}

        protected function
register(){
           
// Cross validation if the request method is POST else it will return "Not Acceptable" status
           
if($this->get_request_method() != "POST"){
               
$this->response('',406);
            }
           
            if(!empty(
$this->_request['email']) && !empty($this->_request['password'])){

               
$check_info = array(
                       
'fields'=>'user_id,email',
                       
'where'=>'email like "'.$this->_request['email'].'"'
                   
);
               
$exist_email = $this->GetSingleRecord("user_master",$check_info);

                if(
count($exist_email)>0) {
                   
$response_array['status']='fail';
                   
$response_array['message']='Email already exists.';
                   
$response_array['data']='';
                   
$this->response($this->json($response_array), 200);
                 } else {
                   
$info_array = array(
                           
'firstname'=>$this->_request['firstname'],
                           
'lastname'=>$this->_request['lastname'],
                           
'email'=>$this->_request['email'],
                           
'password'=>$this->MakePassword($this->_request['password']),
                           
'register_date'=>date("Y-m-d H:i:s"),
                           
'register_ipaddress'=>$_SERVER['REMOTE_ADDR']
                        );
                   
//$this->response($this->json($info_array), 200);
                   
$user_id = $this->InsertRecord("user_master",$info_array);

                    if(
$user_id>0) {
                       
$response_array['status']='success';
                       
$response_array['message']='register successfully.';
                       
$response_array['data']=array('user_id'=>$user_id);
                       
$this->response($this->json($response_array), 200);
                    } else {
                       
$response_array['status']='fail';
                       
$response_array['message']='insufficient data.';
                       
$response_array['data']='';
                       
$this->response($this->json($response_array), 204);
                    }
                }
            }
        }

        protected function
login(){
           
// Cross validation if the request method is POST else it will return "Not Acceptable" status
           
if($this->get_request_method() != "POST"){
               
$this->response('',406);
            }
           
           
$email = $this->_request['email'];
           
$password = $this->_request['password'];

            if(!empty(
$email) && !empty($password) && $this->validate($email,'email')){

               
$info_array = array(
                       
"fields"=>"user_id,firstname,lastname,email,active_status",
                       
"where"=>"email = '".$email."' and password = '".$this->MakePassword($password)."'"
                   
);
               
$user_data = $this->GetSingleRecord("user_master",$info_array);

                if(
count($user_data)>0) {
                   
$response_array['status']='success';
                   
$response_array['message']='logged in successfully.';
                   
$response_array['data']=$user_data;
                   
$this->response($this->json($response_array), 200);
                } else {
                   
$response_array['status']='fail';
                   
$response_array['message']='invalid email or password.';
                   
$response_array['data']='';
                   
$this->response($this->json($response_array));
                }
            }
           
           
// If invalid inputs "Bad Request" status message and reason
           
$error = array('status' => "Failed", "msg" => "Invalid data");
           
$this->response($this->json($error), 400);
        }
       
        protected function
users(){
           
// Cross validation if the request method is GET else it will return "Not Acceptable" status
           
if($this->get_request_method() != "GET"){
               
$this->response('',406);
            }

           
$info_array = array(
                       
"fields"=>"user_id,firstname,lastname,email,active_status"
                   
);
           
$user_data = $this->GetRecord("user_master",$info_array);

            if(
count($user_data)>0) {
               
$response_array['status']='success';
               
$response_array['message']='Total '.count($user_data).' record(s) found.';
               
$response_array['total_record']= count($user_data);
               
$response_array['data']=$user_data;
               
$this->response($this->json($response_array), 200);
            } else {
               
$response_array['status']='fail';
               
$response_array['message']='Record not found.';
               
$response_array['data']='';
               
$this->response($this->json($response_array), 204);
            }
        }

        protected function
deleteuser(){
           
// Cross validation if the request method is DELETE else it will return "Not Acceptable" status
           
if($this->get_request_method() != "DELETE"){
               
$this->response('',406);
            }
           
$id = (int)$this->_request['id'];
            if(
$id > 0){
               
$where = "user_id = '".$id."'";
               
$delete = $this->DeleteRecord("user_master",$where);

                if(
$delete>0) {
                   
$response_array['status']='success';
                   
$response_array['message']='Total '.count($delete).' record(s) Deleted.';
                   
$response_array['data']=$delete;
                   
$this->response($this->json($response_array), 200);
                } else {
                   
$response_array['status']='fail';
                   
$response_array['message']='no record deleted';
                   
$response_array['data']='';
                   
$this->response($this->json($response_array), 200);
                }
            } else {
               
$this->response('',204); // If no records "No Content" status
           
}
        }
    }
   
// Initiiate Library
   
$api = new API();
   
$api->processApi();
?>


Details

REST API with MySQLi - CRUD Operations

Rest API class with MySQLi based CRUD operations and User Module as demo.

Developed By :

Bharat Parmar

Version :

1.0

File Structure :

1) config.php : Configuration File

2) bharatcode.sql : Database File.

3) class/Main.class.php : Main class file which contains many usefull methods for database operations, mail sending, validation.

4) rest/.htaccess : HTACCESS file for the URL redirection

5) rest/Rest.inc.php : This class file contains REST Standard basis api related methods.

Requirements :

1) PHP Version : 3.0 and above

Sample Code :

1) Get Users :

Request :

GET /bharat/restful/rest/users HTTP/1.1 Host: localhost Cache-Control: no-cache Postman-Token: 94ce58e8-5db7-4df4-19e5-457b29586d5f

2) Register User :

Request :

POST /bharat/restful/rest/register HTTP/1.1 Host: localhost Cache-Control: no-cache Postman-Token: ec8d2516-818d-4f3d-a417-9903575ccf81 Content-Type: application/x-www-form-urlencoded

Parameters : firstname, lastname, email, password firstname=Jack&email=jackthomas@gmail.com&lastname=Thomas&password=123456

Response :

{ "status": "success", "message": "register successfully.", "data": {

"user_id": 11

} }

3) Delete User :

Request :

DELETE /bharat/restful/rest/deleteuser?id=11 HTTP/1.1 Host: localhost Cache-Control: no-cache Postman-Token: 79e1e8cb-60a8-993a-7e63-d2831ed9ac16 Content-Type: multipart/form-data;

Response :

{ "status": "success", "message": "Total 1 record(s) Deleted.", "data": 1 }

4) Login :

Request :

POST /bharat/restful/rest/login HTTP/1.1 Host: localhost Cache-Control: no-cache Postman-Token: 651c7ef3-da80-0624-f519-b4ca8d39e8f5 Content-Type: application/x-www-form-urlencoded

Parameters : email, password email=jackthomasgmail.com&password=123456

Response :

{ "status": "success", "message": "logged in successfully.", "data": {

"user_id": 11

} }


  Files folder image Files (7)  
File Role Description
Files folder imageclass (1 file)
Files folder imagerest (3 files)
Accessible without login Plain text file bharatcode.sql Data Database File
Accessible without login Plain text file config.php Conf. Configuration file
Accessible without login Plain text file README.md Doc. Read Me file

  Files folder image Files (7)  /  class  
File Role Description
  Plain text file Main.class.php Class Main class file which includes CRUD methods

  Files folder image Files (7)  /  rest  
File Role Description
  Accessible without login Plain text file .htaccess Data htaccess file for rest
  Accessible without login Plain text file api.php Example REST API methods
  Plain text file Rest.inc.php Class REST class

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:979
This week:1
All time:3,713
This week:34Up
 User Ratings  
 
 All time
Utility:91%StarStarStarStarStar
Consistency:83%StarStarStarStarStar
Documentation:58%StarStarStar
Examples:75%StarStarStarStar
Tests:-
Videos:-
Overall:67%StarStarStarStar
Rank:453