Latest web development tutorials

PHP RESTful

REST (English: Representational State Transfer, called REST), refers to a set of architectural constraints and principles.

REST-style Web API design is called a RESTful API. It is defined from the following three resources:

  • Intuitive brief address resource: URI, for example: http://example.com/resources/ .
  • Transmission resource: Web service accepts the return of Internet media types, such as: JSON, XML, YAM like.
  • Operation of resources: Web service method in a series of requests on the resource supported (eg: POST, GET, PUT or DELETE).

This tutorial we will use the PHP (no frame) to create a RESTful web service, you can download at the end of the article to use the code in this section.

In this tutorial, you will learn the following:

  • Create a RESTful Webservice.
  • Using native PHP, does not depend on any framework.
  • REST URI pattern to follow the rules.
  • RESTful service accepts and format may be returned JSON, XML and so on.
  • HTTP status codes corresponding response depending on the situation.
  • Demo requests header.
  • Use REST client to test RESTful web service.

Examples of RESTful Webservice

The following code is RESTful service class Site.php:

Examples

<? php
/ *
* This tutorial demonstrates examples of RESTful
* RESTful service class
* /
Class Site {

private $ sites = array (
1 => 'TaoBao',
2 => 'Google',
3 => 'w3big',
4 => 'Baidu',
5 => 'Weibo',
6 => 'Sina'

);


public function getAllSite () {
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 a brief visual resources address. .htaccess Apache server should be set up corresponding Rewrite rules.

This example we will use two URI rules:

1, to obtain a list of all sites:

http://localhost/restexample/site/list/

2, using the id for the specified site, the following URI to get the id of 3 sites:

http://localhost/restexample/site/list/3/

.htaccess File configuration rules of the project 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=$1 [nc,qsa]

RESTful Web Service Controller

In the.htaccess file, we'll get RestController.php file the corresponding request by setting the parameter 'view', by getting the 'view' different parameters to distribute to different methods.RestController.php file code is as follows:

Examples

<? php
require_once ( "SiteRestHandler.php");

$ view = "";
if (isset ($ _GET & # 91; "view" & # 93;))
$ view = $ _GET & # 91 ; "view" & # 93 ;;
/ *
* RESTful service controller
* URL mapping
* /
switch ($ view) {

case "all":
// Handle REST Url / site / list /
$ siteRestHandler = new SiteRestHandler ();
$ siteRestHandler -> getAllSites ();
break;

case "single":
// Handle REST Url / site / show / < id> /
$ siteRestHandler = new SiteRestHandler ();
$ siteRestHandler -> getSite ($ _GET [ "id"]);
break;

case "":
// 404 - not found;
break;
}
?>

Simple RESTful Foundation Classes

The following provides a base class RESTful for processing in response to the request of the HTTP status code, SimpleRest.php file code is as follows:

Examples

<? php
/ *
* A simple RESTful web services base class
* We can extend this class based on demand
* /
class SimpleRest {

private $ httpVersion = "HTTP / 1.1 ";

public function setHttpHeaders ($ contentType, $ statusCode) {

$ statusMessage = $ this -> getHttpStatusMessage ($ statusCode);

header ($ this -> httpVersion " " $ statusCode.. "" $ statusMessage..);
header ( "Content-Type:" $ 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 handler class SiteRestHandler.php, inherited the above we provide RESTful base class, the class is determined by the parameters of the request to determine if the returned HTTP status codes and data formats, we provide examples of three data formats: "application / json", "application / xml" or "text / html":

SiteRestHandler.php file code is as follows:

Examples

<? php
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) {
// Create an object SimpleXMLElement
$ xml = new SimpleXMLElement ( '< site> </ site> <xml version = "1.0"??>');
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 through http: // localhost / restexample / site / list / visit, the output results are as follows:


RESTful Web Service Client

Then we can use the Google Chrome browser's "Advance Rest Client" as RESTful Web Service clients to request our services.

Examples of the request http: // localhost / restexample / site / list / address, the received data is similar toAccept: application / json

3 request id site w3big (tutorial), access address is http: // localhost / restexample / site / list / 3 /,

Source download

The code used in the example to click the button below to download:

Source download