PHP RESTful
REST (Representational State Transfer) refers to a set of architectural constraints and principles.
A Web API that conforms to the REST design style is called a RESTful API. It is defined from the following three aspects of resources:
- Intuitive and concise resource addresses: URI, for example:
http://example.com/resources/. - Transmitted resources: the Internet media types that the web service accepts and returns, such as JSON, XML, YAML, etc.
- Operations on resources: the set of request methods supported by the web service on that 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.
- Use native PHP, without depending on any framework.
- The URI pattern needs to follow REST rules.
- A RESTful service can accept and return formats such as JSON, XML, etc.
- Respond with the corresponding HTTP status code according to different situations.
- Demonstrate the use of request headers.
- Use a REST client to test the RESTful web service.
RESTful Webservice Example
The following code is the RESTful service class Site.php:
Example
' TaoBao ' , 2 => ' Google ' , 3 => ' Runoob ' , 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
A RESTful Services URI should be set to an intuitive and concise resource address. The Apache server's .htaccess should have the corresponding Rewrite rules configured.
In this example we will use two URI rules:
1. Get the list of all sites:
http://localhost/restexample/site/list/
2. Get a specified site by id; the following URI gets the site with id 3:
http://localhost/restexample/site/list/3/
The **.htaccess** file configuration rules for the project are shown below:
# Enable rewrite feature
Options +FollowSymlinks
RewriteEngine on
# Rewrite rules
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 .htaccess In the file, we obtain the corresponding request in the RestController.php file by setting the 'view' parameter, and dispatch to different methods by obtaining different 'view' parameters. The **RestController.php** file code is as follows:
Example
getAllSites ( ) ; break ; case " single " : // handle REST Url /site/show/A simple RESTful base class
Below is a base class for RESTful that handles the HTTP status code of the response request,SimpleRest.php The file code is as follows:
Example
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 Handler Class
Below is a RESTful Web Service handler class SiteRestHandler.php, which inherits from the RESTful base class we provided above. The class determines the returned HTTP status code and data format by judging the request parameters. In the example we provide three data formats: "application/json", "application/xml" or "text/html":
SiteRestHandler.php The file code is as follows:
Example
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 = "| " . $key . " | " . $value . " |
'
)
;
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 it via http://localhost/restexample/site/list/ and the output is as follows:
RESTful Web Service Client
Next we can use Google Chrome's "Advance Rest Client" as a RESTful Web Service client to request our service.
In the example, the request is made to the address http://localhost/restexample/site/list/ and the received data is similar to Accept: application/json

To request the site with id 3, Runoob (Runoob Tutorial), 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 button below: