PHP RESTful
REST (English: Representational State Transfer, referred to as REST) refers to a set of architectural constraints and principles.
Web API that conforms to the REST design style is called RESTful API. It is defined from the following three aspects of resources:
Intuitive and short resource address: URI, such as:
http://example.com/resources/
.Transmitted resources: Internet media types accepted and returned by the web service, such as: JSON, XML, YAM, etc.
Operations on resources: A series of request methods supported by the Web service on the resource (such as: POST, GET, PUT or DELETE).
In this tutorial we will use PHP (without a framework) to create a RESTful web service. At the end of the article you can download the code used in this chapter.
Through this tutorial you will learn the following:
Create a RESTful Webservice.
Uses native PHP and does not rely on any framework.
URI patterns need to follow REST rules.
RESTful service accepts and returns formats that can be JSON, XML, etc.
Respond to the corresponding HTTP status code according to different situations.
Demonstrates the use of request headers.
Use REST client to test RESTful web service.
RESTful Webservice instance
The following code is the RESTful service class Site.php:
Example
/*
* php Chinese website RESTful demonstration example
* RESTful service Class
*/
Class Site {
private $sites = array(
##=> php', 5 => 'Weibo'
, #'Sina' # return $this
->sites; } public function getSite($id){
$site = array($id => ($this->sites[$id]) ? $this->sites[$id] : $this->sites[1]);
return $site;
}
}
?>
RESTful Services URI mapping
RESTful Services URI should be set to an intuitive and short resource address. The .htaccess of the Apache server should have corresponding Rewrite rules set.
In this example we will use two URI rules:
1. Get a list of all sites:
http://localhost/restexample/site/list/
2. Use the id to get the specified site, the following URI is to get the id For the site of 3:
http://localhost/restexample/site/list/3/
The .htaccess file configuration rules are as follows:
# 开启 rewrite 功能 Options +FollowSymlinks RewriteEngine on # 重写规则 RewriteRule ^site/list/$ RestController.php?view=all [nc,qsa] RewriteRule ^site/list/([0-9]+)/$ RestController.php?view=single&id= [nc,qsa]
RESTful Web Service Controller
In the .htaccess file, we set the parameter 'view' to obtain the corresponding request in the RestController.php file, and distribute it to different methods by obtaining different parameters of 'view'. RestController.php The file code is as follows:
实例
require_once("SiteRestHandler.php");
$view = "";
if(isset($_GET["view"]))
$view = $_GET["view"];
/*
* RESTful service 控制器
* URL 映射
*/
switch($view){
case "all":
// 处理 REST Url /site/list/
$siteRestHandler = new SiteRestHandler();
$siteRestHandler->getAllSites();
break;
case "single":
// 处理 REST Url /site/show/<id>/
$siteRestHandler = new SiteRestHandler();
$siteRestHandler->getSite($_GET["id"]);
break;
case "" :
//404 - not found;
break;
}
?>
Simple RESTful base class
The following provides a RESTful base class for processing HTTP status codes in response to requests. SimpleRest.php The file code is as follows:
Example
/*
* A simple RESTful web services base class
* We can extend the requirements based on this class
*/
class SimpleRest {
private $httpVersion = "HTTP/1.1";
public function setHttpHeaders($contentType, $statusCode){
=
$this -> getHttpStatusMessage($statusCode); ##" ".
$statusCode
." ". $statusMessage); ##$contentType); } public function getHttpStatusMessage($statusCode){ $httpStatus = 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 ($httpStatus[$statusCode]) ? $httpStatus[$statusCode] : $status[500];
}
}
?>
RESTful Web Service processing class
The following is a RESTful Web Service processing class SiteRestHandler.php, which inherits the RESTful base class we provided above. The class determines the returned HTTP status code by judging the request parameters. And data format, in the example we provide three data formats: "application/json", "application/xml" or "text/html":
SiteRestHandler.php The file code is as follows :
实例
require_once("SimpleRest.php");
require_once("Site.php");
class SiteRestHandler extends SimpleRest {
function getAllSites() {
$site = new Site();
$rawData = $site->getAllSite();
if(empty($rawData)) {
$statusCode = 404;
$rawData = array('error' => 'No sites found!');
} else {
$statusCode = 200;
}
$requestContentType = $_SERVER['HTTP_ACCEPT'];
$this ->setHttpHeaders($requestContentType, $statusCode);
if(strpos($requestContentType,'application/json') !== false){
$response = $this->encodeJson($rawData);
echo $response;
} else if(strpos($requestContentType,'text/html') !== false){
$response = $this->encodeHtml($rawData);
echo $response;
} else if(strpos($requestContentType,'application/xml') !== false){
$response = $this->encodeXml($rawData);
echo $response;
}
}
public function encodeHtml($responseData) {
$htmlResponse = "<table border='1'>";
foreach($responseData as $key=>$value) {
$htmlResponse .= "<tr><td>". $key. "</td><td>". $value. "</td></tr>";
}
$htmlResponse .= "</table>";
return $htmlResponse;
}
public function encodeJson($responseData) {
$jsonResponse = json_encode($responseData);
return $jsonResponse;
}
public function encodeXml($responseData) {
// 创建 SimpleXMLElement 对象
$xml = new SimpleXMLElement('<?xml version="1.0"?><site></site>');
foreach($responseData as $key=>$value) {
$xml->addChild($key, $value);
}
return $xml->asXML();
}
public function getSite($id) {
$site = new Site();
$rawData = $site->getSite($id);
if(empty($rawData)) {
$statusCode = 404;
$rawData = array('error' => 'No sites found!');
} else {
$statusCode = 200;
}
$requestContentType = $_SERVER['HTTP_ACCEPT'];
$this ->setHttpHeaders($requestContentType, $statusCode);
if(strpos($requestContentType,'application/json') !== false){
$response = $this->encodeJson($rawData);
echo $response;
} else if(strpos($requestContentType,'text/html') !== false){
$response = $this->encodeHtml($rawData);
echo $response;
} else if(strpos($requestContentType,'application/xml') !== false){
$response = $this->encodeXml($rawData);
echo $response;
}
}
}
?>
Next we access through http://localhost/restexample/site/list/, the output results are as follows:
RESTful Web Service Client
Next we can use the "Advance Rest Client" of the Google Chrome browser as a RESTful Web Service client to request our services.
In the example, the http://localhost/restexample/site/list/ address is requested, and the received data is similar to Accept: application/json
Request the site php with ID 3 (php Chinese website), the access address is http://localhost/restexample/site/list/3/,
source code Download
The code used in the example can be downloaded by clicking the following button:
Source code download