Riaxe Systems | Blog
Riaxe.com

Jun
9th
REST API
Author :Alex Parker

API : Application program interface (API) is a set of routines, protocols, and tools for building software applications.PHP offers three different APIs to connect to MySQL(mysql, mysqli, and PDO extensions). REST API : REST API is simple stateless architecture that runs over HTTP. It allows users to interact with your website from anything that can […]

Date : June 9, 2017
No Comments

REST API

API : Application program interface (API) is a set of routines, protocols, and tools for building software applications.PHP offers three different APIs to connect to MySQL(mysql, mysqli, and PDO extensions).

follow link REST API : REST API is simple stateless architecture that runs over HTTP. It allows users to interact with your website from anything that can send an HTTP request. REST has become the standard design architecture for developing web APIs. It consists of Client and Server. Client initiates request to server,servers process requests and return appropriate responses. The responses can be sent as XML or JSON. Request utilize HTTP verbs(GET,POST,PUT,DELETE,etc.) which are used to manage the state of resources.

STATELESS AND STATEFUL : A stateful server keeps state between connections. A stateless server does not. So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request.

When you send a request to a stateless server, it does not create any object that tracks information regarding your requests.
In REST applications, there must not be session state stored on the server side. Instead, it must be handled entirely by the client.To implement state on top of that you can use sessions, databases, shared memory, files or anything else that somehow retains state.

http://mujerguatemala.org/nature-essay/ HTTP:The Hypertext Transfer Protocol (HTTP) is a networking protocol for distributed information systems. HTTP is the foundation of data communication for the World Wide Web/Internet. Most website URLs include the http:// protocol at the beginning of the address, however the https:// protocol may also be used for transferring data with encryption.

In this Blog I will show you how to create a Restful webservice in plain php (without using framework).

In REST design the URL endpoints should be well formed and should be easily understandable. Every URL for a resource should be uniquely identified.

go site Ex: http://example.com/bike/list (to show the list of the bikes)
http://example.com/bike/list/1 (to show bike name whose id is 1)

.htaccess file maps your request url and forwards request to controller.

.htaccess
# Turn rewrite engine on
RewriteEngine on

RewriteRule ^bike/list/([0-9]+) Controller.php?view=single&id=$1 [qsa]
RewriteRule ^bike/list Controller.php?view=all [qsa]

htaccess file forwarding request to controller with key like “view” to identify the request and controller forwarded to handler class.

Controller.php

require_once("BikeHandler.php");		
$view = "";
if(isset($_GET["view"]))
	$view = $_GET["view"];
switch($view){
	case "all":
		$BikeHandler = new BikeHandler();
		$BikeHandler->getAllBikes();
		break;
	case "single":
		$BikeHandler = new BikeHandler();
		$BikeHandler->getBike($_GET["id"]);
		break;
}

Make sure your API is sending the Content-Type header to tell the client to expect a JSON response. Here I am using only json response type.

Research Paper For College Students BikeHandler.php

require_once("Rest.inc.php");
require_once("Bike.php");
class BikeHandler extends Rest {
	function getAllBikes() {	
		$bike = new Bike();
		$data = $bike->getAllBike();
		if(empty($data)) {
			$statusCode = 404;
			$data = array('error' => 'No bikes found!');		
		} else {
			$statusCode = 200;
		}
 
		$requestContentType = 'application/json';
		$this ->setHttpHeaders($requestContentType, $statusCode);
		$response = json_encode($data);
		echo $response;		
	}
	public function getBike($id) {
		$bike = new Bike();
		$data = $bike->getBikeById($id);
		if(empty($data)) {
			$statusCode = 404;
			$data = array('error' => 'No bike found!');		
		} else {
			$statusCode = 200;
		}
		$requestContentType = 'application/json';
		$this ->setHttpHeaders($requestContentType, $statusCode);		
		$response = json_encode($data);
		echo $response;		
	}
}

HTTP status codes in the response body tells client application what action should be taken with the response. For an example if the response code 200, it means on the server side the request is processed successfully and you can expect updated data in the response. As well if the status code is 401, the request is not authorized. A possible cause for 401 could be api key is invalid.

Following class has a couple of methods that can be commonly used in all REStful service. One method is used to construct the response and another method is to hold the different HTTP status code and its respective messages. Such common methods can be added to this class and this can be made a base class for all RESTful handler classes.

follow url Rest.inc.php

class Rest {
	
	private $httpVersion = "HTTP/1.1";
 
	public function setHttpHeaders($contentType, $statusCode){	
		$statusMessage = $this ->getStatusMessage($statusCode);
		header($this->httpVersion. " ". $statusCode ." ". $statusMessage);		
		header("Content-Type:". $contentType);
	}
	
	public function getStatusMessage($statusCode){
		$status = array(
			100 => 'Continue',  
			101 => 'Switching Protocols',  
			200 => 'OK',
			201 => 'Created',  
			202 => 'Accepted',  
			203 => 'Non-Authoritative Information',  
			204 => 'No Content',  
			205 => 'Reset Content',  
			206 => 'Partial Content',  
			300 => 'Multiple Choices',  
			301 => 'Moved Permanently',  
			302 => 'Found',  
			303 => 'See Other',  
			304 => 'Not Modified',  
			305 => 'Use Proxy',  
			306 => '(Unused)',  
			307 => 'Temporary Redirect',  
			400 => 'Bad Request',  
			401 => 'Unauthorized',  
			402 => 'Payment Required',  
			403 => 'Forbidden',  
			404 => 'Not Found',  
			405 => 'Method Not Allowed',  
			406 => 'Not Acceptable',  
			407 => 'Proxy Authentication Required',  
			408 => 'Request Timeout',  
			409 => 'Conflict',  
			410 => 'Gone',  
			411 => 'Length Required',  
			412 => 'Precondition Failed',  
			413 => 'Request Entity Too Large',  
			414 => 'Request-URI Too Long',  
			415 => 'Unsupported Media Type',  
			416 => 'Requested Range Not Satisfiable',  
			417 => 'Expectation Failed',  
			500 => 'Internal Server Error',  
			501 => 'Not Implemented',  
			502 => 'Bad Gateway',  
			503 => 'Service Unavailable',  
			504 => 'Gateway Timeout',  
			505 => 'HTTP Version Not Supported');
		return $status[$statusCode];
	}
}

Bike.php

Class Bike {
	private $bikes = array(
		1 => 'Pulsar',  
		2 => 'Apache',  
		3 => 'Boxer',  			
		4 => 'Harley',  			  
		5 => 'Gixxer');
	public function getAllBike(){
		return $this->bikes;
	}
	
	public function getBikeById($id){
		$bikes = array($id => $this->bikes[$id]);
		return $bikes;
	}	
}

see url Web service Client:

To test a RESTful web service I am using Google Chrome plugin REST client. You need to add the extension and use it as below. Following is the screen shots of testing the above example RESTful web service.

api-image


Article by : Jitendra Kumar Mohanta
Sr. Magento Developer
Linkedin | Stackoverflow

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *


*