How to Build a Simple REST API in PHP?

In this tutorial, I'll teach you how to build a simple REST API with PHP and MySQL.

REST has become the de facto standard when it comes to exposing data via APIs and building web services. In fact, most web applications these days access and expose data via REST APIs. With the popularity of front-end frameworks that can consume REST APIs effortlessly, it’s always going to be a plus for you if your web application exposes REST APIs.

In this article, we’ll build a simple demo application, which allows you to fetch a list of users from the MySQL database via a REST endpoint.

Setting Up the Skeleton

In this section, we’ll briefly go through the project structure.


Let’s have a look at the following structure.

├── libs

│       ├── dragan_config.php

│       └── dragan_libs.php

├── index.php

..
Let’s try to understand the project structure.

index.php: the entry-point of our application. It will act as a front controller of our application.

libs/dragan_config.php: holds the configuration information of our application. Mainly, it will hold the database credentials.

libs/dragan_libs.php:  base controller file which holds common utility methods.

..

In this index.php

<?php
 header('Access-Control-Allow-Origin: *');

#..............................................................................
# Supporting library : dragan_libs.php
	include("libs/dragan_libs.php");
	$dl = new Libs();
	
    $common_path="https://tekheist.com/";
    
	//$connection =  $dl->getConnstring();
#..............................................................................
	 //$check_status=$_REQUEST["status"];
	 $check_status = $dl->draganVariable($_REQUEST['status'],"text");
	
     switch($check_status){
     
           
            # http://training.businessdragan.com/bd4/kumki/index.php?status=staff_view_pagination&page=1
            case 'cart_products':
                // pagination rest api : contact tekheist.com
            
           #https://tekheist.com/software/api/index.php?status=cart_home
            case 'cart_home':
           	     
           	            	 $query="SELECT GROUP_CONCAT(`category_name`) AS category FROM cart_category WHERE `status`=0";
                             $row_categories = $dl->draganQuery("select",$query,"object");	
        
                                $json["layout"]         = 1;
                                $json["title"]          = "Tek Shop";
                                $json["description"]    = "Discover our new products..";
                                $json["category"]       = $row_categories["category"];
           
                              $dl->jsonResponse($json); 
           	     
            	break;
            # .................................
            
    		default:
    		    //echo "Authorization failed: "."<b>"."Invalid API Key"."</b><br>"."Automatically report details of possible security incidents to admin (your MAC address is submited)";
                echo "404. That’s an error. The requested URL was not found on this server. That’s all we know.";
            	break;
    }
#..............................................................................
#..............................................................................

?>
..

libs/dragan_config.php

<?php
Class dbObj{
	/* Database connection start */
	var $servername = "localhost";
	var $username   = "tekAdmin";
	var $password   = "123456";
	var $dbname     = "db_tek";
	var $conn;
	
	function getConnstring() {
		$con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());
 
 // framework use    
$GLOBALS['dragan_grant_access'] =$con;



		/* check connection */
		if (mysqli_connect_errno()) {
			printf("Connect failed: %s\n", mysqli_connect_error());
			exit();
		} else {
			$this->conn = $con;
		}
		return $this->conn;
	}
}

?>
..
libs/dragan_libs.php
<?php
#..............................................................................
# Connect to database : dragan_config.php
	include("dragan_config.php");
	$db = new dbObj();
	$connection =  $db->getConnstring();
#.............................................................................. 
Class Libs{
// image upload plan to add 
//..............................................................................
function jsonResponse($data) {//$status,$status_message,
    
    header('Content-Type: application/json');
	
//	$response['status']         = $status;
	//$response['status_message'] = $status_message;
	
	
	//$response["data"]          = $data;
	//	$response["data"]          = $data;
	
	
	
	// * if no error it works fine 
	$json_response              = json_encode($data);

    // * if there is an error (it will show what is an error) 
    if($json_response === false || is_null($json_response)){
    
        // Get the last JSON error.
        $jsonError = json_last_error();
    
        //Use a switch statement to figure out the exact error.
        switch($jsonError){
             
            case JSON_ERROR_DEPTH:
                    $error .= 'Maximum depth exceeded!';
                    break;
            case JSON_ERROR_STATE_MISMATCH:
                    $error .= 'Underflow or the modes mismatch!';
                    break;
            case JSON_ERROR_CTRL_CHAR:
                    $error .= 'Unexpected control character found';
                    break;
            case JSON_ERROR_SYNTAX:
                    $error .= 'Malformed JSON';
                    break;
            case JSON_ERROR_UTF8:
                    $error .= 'Malformed UTF-8 characters found!'; 
                    break;
            default:
                    $error .= 'Unknown error!';
                    break;
        }
                
	$response['status']          = false;
	$response['status_message']  = "Could not encode JSON : ".$error;
	$response['data']            = null;
    $json_response               = json_encode($response);
    }
    
	echo $json_response; 
}
//..............................................................................
/**
 * @ draganQuery
 * 
 * @ $status : select,insert,update
 * @ $query  : your query
 * @ $value  : select - page id, update id  
 * */
function draganQuery($status,$query,$value){
	global $connection;
	
	// Adding results to an array 
	$response=array();
	
		switch($status){
		     #.................................
		     case 'select':
		         
		         if($value=="array"){
		                //	$result=mysqli_query($connection, $query) or die(" <pre>Error code : " . mysqli_errno($connection) ."<br>".  "Error message :  ". mysqli_error($connection)."<br>".  "Error list : ". print_r(mysqli_error_list($connection))."</pre>");
		            	$result=mysqli_query($connection, $query) or die("<b>Error code :</b> " . mysqli_errno($connection) ."<br><br>".  "<b>Error message :  </b>". mysqli_error($connection));
		            	
    
		            	if (mysqli_num_rows($result) > 0) {
                    		while($row=mysqli_fetch_assoc($result))
                    		{
                    			$response[]=$row;
                    		}
		            	}else{
		            	    $response="no data";
		            	}
		            	
		            	 // Free result set
                         mysqli_free_result($result);
                		
		         }
		         else if($value=="object"){
		            	$result=mysqli_query($connection, $query) or die("<b>Error code :</b> " . mysqli_errno($connection) ."<br><br>".  "<b>Error message :  </b>". mysqli_error($connection));
		            	
		            /*	 if (mysqli_num_rows($result) > 0) {
		            	   $response=mysqli_fetch_array($result,MYSQLI_ASSOC);
		            	 }else{
		            	      $response ="";
		            	 }*/
		            	  $response=mysqli_fetch_array($result,MYSQLI_ASSOC);
		            
		         }
		         else{
		                    // Getting the page number which is to be displayed  
                             $page = $value; // or  $_REQUEST['page'];
                             
                             // Initially we show the data from 1st row that means the 0th row 
                             $start = 0; 
                             
                             // Limit is 10 that means we will show 10 items at once
                             $limit = 10;
                             
                             // Counting the total item available in the database 
                             $total_rows = mysqli_query($connection, $query) or die("<b>Error code :</b> " . mysqli_errno($connection) ."<br><br>".  "<b>Error message :  </b>". mysqli_error($connection));
                             $total_rows = mysqli_num_rows($total_rows);
                             
                  
                             // We can go atmost to page number $total_rows/limit
                             $page_limit = $total_rows/$limit; 
                             
                             // If the page number is more than the limit we cannot show anything 
                             
                             // if($page<=$page_limit){
                            if (!empty($value)) { 
                            
                             // Calculating start for every given page number 
                             $start = ($page - 1) * $limit; 
                            
                             // SQL query to fetch data of a range 
                             $sql = $query." LIMIT $start, $limit";
                            
                             $result = mysqli_query($connection,$sql) or die("<b>Error code :</b> " . mysqli_errno($connection) ."<br><br>".  "<b>Error message :  </b>". mysqli_error($connection));
                            
                    
                 
                         
                            if (mysqli_num_rows($result) > 0) {
                        		while($row=mysqli_fetch_assoc($result))
                        		{
                        			$response[]=$row;
                        		}
    		            	}else{
    		            	    $response="no data";
    		            	}
		            	
    		            	 // Free result set
                             mysqli_free_result($result);
 
 
		  
		       
 
 
 
 
                            }
    
    
    
		         }
		     break;
		     #.................................
		     case 'insert':
		            
		            	$result=mysqli_query($connection, $query) or die("<b>Error code :</b> " . mysqli_errno($connection) ."<br><br>".  "<b>Error message :  </b>". mysqli_error($connection));
		            	$last_insert_id = mysqli_insert_id($connection);  
		            	    
		            	if ($last_insert_id > 0) {
                    		 $response=$last_insert_id;
		            	}else{
		            	    $response="no data";
		            	}

		     break;
		    	     #.................................
		     case 'update':
		            
		            	$result=mysqli_query($connection, $query) or die("<b>Error code :</b> " . mysqli_errno($connection) ."<br><br>".  "<b>Error message :  </b>". mysqli_error($connection));
		            	//$last_insert_id = mysqli_insert_id($connection);  
		            	    
		                if(mysqli_affected_rows($connection)== 1 ){ 
                    		 $response="data saved";
		            	}else{
		            	    $response="no data";
		            	}

		     break;
		     #.................................
		}
		
	
		
		//return the array in json format 
	    return $response;
}
//..............................................................................
function draganVariable($variable,$type) {
    if($type=="checkbox"){
        $temp_var = isset($variable) ? $variable : "";
        return ($temp_var=="on") ? 0 : 1;
    }
    else if($type=="capital_text"){
       // $temp_var = isset($variable) ? $variable : "";
        return isset($variable) ? ucfirst(strtolower($variable)) : "";
    }
    else if($type=="time"){
        //$temp_var = isset($variable) ? $variable : "";
        return isset($variable) ? date('H:i:s', strtotime(str_replace('/', '-', $variable))) : "";
    }
	else if($type=="select2"){
		
		$this_variable = implode(',',$variable);
        return isset($this_variable) ? $this_variable : "";
      
    }
	else if($type=="date"){
        //$temp_var = isset($variable) ? $variable : "";
        return isset($variable) ? date('Y-m-d', strtotime(str_replace('-', '/', $variable))) : "";
    }
    else if($type=="date_time"){
        //$temp_var = isset($variable) ? $variable : "";
        return isset($variable) ? date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $variable))) : "";
    }
    else if($type=="date_range"){
          $temp_var = isset($variable) ? $variable : "";
          $date_range       = (explode(" - ",$temp_var));
          $from_date  = date('Y-m-d',strtotime($date_range[0]));
          $to_date    = date('Y-m-d',strtotime($date_range[1]));
          return isset($variable) ? array('from_date' => $from_date,'to_date' => $to_date) : "";
    }
    else if($type=="secure"){
          $variable = trim($variable);
          $variable = stripslashes($variable);
          $variable = htmlspecialchars($variable);
          return $variable;
    }
    // check email/ mobile no / email
    return isset($variable) ? $variable : "";
}
//..............................................................................
}
#..............................................................................
//http://php.net/manual/en/function.http-response-code.php
//https://phppot.com/php/php-restful-web-service/
// dragan variable : https://www.w3schools.com/php/php_exception.asp
//https://www.w3schools.com/php/func_mysqli_num_rows.asp
    # HTTP response codes and messages	
	/* if ($status !== NULL) {
                switch ($status) {
                    case 100: $text = 'Continue'; break;
                    case 101: $text = 'Switching Protocols'; break;
                    case 200: $text = 'OK'; break;
                    case 201: $text = 'Created'; break;
                    case 202: $text = 'Accepted'; break;
                    case 203: $text = 'Non-Authoritative Information'; break;
                    case 204: $text = 'No Content'; break;
                    case 205: $text = 'Reset Content'; break;
                    case 206: $text = 'Partial Content'; break;
                    case 300: $text = 'Multiple Choices'; break;
                    case 301: $text = 'Moved Permanently'; break;
                    case 302: $text = 'Moved Temporarily'; break;
                    case 303: $text = 'See Other'; break;
                    case 304: $text = 'Not Modified'; break;
                    case 305: $text = 'Use Proxy'; break;
                    case 400: $text = 'Bad Request'; break;
                    case 401: $text = 'Unauthorized'; break;
                    case 402: $text = 'Payment Required'; break;
                    case 403: $text = 'Forbidden'; break;
                    case 404: $text = 'Not Found'; break;
                    case 405: $text = 'Method Not Allowed'; break;
                    case 406: $text = 'Not Acceptable'; break;
                    case 407: $text = 'Proxy Authentication Required'; break;
                    case 408: $text = 'Request Time-out'; break;
                    case 409: $text = 'Conflict'; break;
                    case 410: $text = 'Gone'; break;
                    case 411: $text = 'Length Required'; break;
                    case 412: $text = 'Precondition Failed'; break;
                    case 413: $text = 'Request Entity Too Large'; break;
                    case 414: $text = 'Request-URI Too Large'; break;
                    case 415: $text = 'Unsupported Media Type'; break;
                    case 500: $text = 'Internal Server Error'; break;
                    case 501: $text = 'Not Implemented'; break;
                    case 502: $text = 'Bad Gateway'; break;
                    case 503: $text = 'Service Unavailable'; break;
                    case 504: $text = 'Gateway Time-out'; break;
                    case 505: $text = 'HTTP Version not supported'; break;
                    default:
                        exit('Unknown http status code "' . htmlentities($code) . '"');
                    break;
                }
	 }        */
	 
?>

A REST API is good for communication between an app and a server.

Android & IOS App Using PHP and MySQL.

When we send a user request to the server using an Android /IOS server the response from your request is fast in JSON format. REST API is very simple compared to any other method.


Comments