PHP RESTful Web Services Tutorial With Example

By PHP RESTful Web Services Tutorial With Example

In this tutorial, we will learn how to create a PHP RESTful web service. REST stands for Representational State Transfer is the most common architectural style of developing web services. The style has its rules and constraints to design and develop web services that can be accessed externally. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet.

We will build a RESTful web service in PHP without using any framework. The REST service will provide data to an external mobile or web application based on the request made to it. The client will access data from the web service by sending a request. The request consists of a URI, usually called endpoint, and a set of parameters with the selected method, GET, or POST.

Before building an example, let’s understanding REST, its constraints, its architecture, and uses.

What is RESTful?

REST stands for Representational State Transfer. It is an architecture that enables the communication between several computer systems. The term REST was first coined in 2000 by Roy T. Fielding in his doctoral dissertation.  REST is defined by a set of rules, constraints, and principles. Applications that satisfy these principles are called RESTful. Web services that follow RESTful guidelines are called RESTful services. And the URI is used to access the RESTful service to get resources. 

REST Constraints

  • Client-Server architecture
  • Statelessness
  • Uniform interface
  • Layered system
  • Cacheability
  • Code on Demand
  • RESTful web services API architecture

The following diagram represents the architecture of a RESTful web service. The database contains the resources being accessed. The RESTful web service controls the flow of resources. It receives a request from the REST client and processes it and later on sends back a response. The arrows represent the request-response flow among the client-server. Based on the web service the resource can be XML feed, JSON data.

Uses of RESTful API

A RESTful API provides services to access data from external applications or REST clients. The following are the uses of RESTful API.

  1. Used as an interface that is used to access resources from external applications built in different languages like Java, PHP, and Android etc.
  2. It is used to transmit data over HTTP
  3. Used to support a wide range of clients once REST constraints are met.

PHP RESTful web service example

To build a good PHP Restful web service, we will create a project to show the names of six US presidents. The project contains the following files:

  1. President.php
  2. PresidentRestHandler.php
  3. RestController.php
  4. SimpleRest.php
  5. .htaccess

The class President contains an array with the names of these presidents. Donald Trump, Barack Obama, George W. Bush, Bill Clinton, George H. W. Bush, and Ronald Reagan. The following is the code of class President.

Class President {

private $presidents = array(
1 => 'Donald Trump',  
2 => 'Barack Obama',  
3 => 'George W. Bush', 
4 => 'Bill Clinton', 
5 => 'George H. W. Bush',  
6 => 'Ronald Reagan');

public function getAllPresidents(){
return $this->presidents;

public function getPresident($id){

$president = array($id => ($this->presidents[$id]) ? $this->presidents[$id] : $this->presidents[1]);
return $president;

RESTful services URI mapping

The .htaccess file is used for mapping the request URI to the REST service endpoint. Let’s see how the URI is mapped. Every resource is accessed via a URI. URI stands for Uniform Resource Identifier and is a compact sequence of characters that identifies an abstract or physical resource. In the example, we have two URIs for accessing the web service from a REST client. One URI is used to get all the presidents in a JSON format while the other one is used to get one president when given an id.

The following is the code for .htaccess file

# Turn rewrite engine on
Options +FollowSymlinks
RewriteEngine on
# map neat URL to internal URL
RewriteRule ^president/list/$   RestController.php?view=all [nc,qsa]
RewriteRule ^president/list/([0-9]+)/$   RestController.php?view=single&id=$1 [nc,qsa]

RESTful web service controller

We are forwarding all the requests to the RestController.php file. We specify the part of the REST controller by providing a key. In our example, we have a key named view. If the value of view is all, then the controller gets all presidents and if the value is single it picks one president whose id is the value of key id. 

The following is the code for RestController.php


$view = "";
$view = $_GET["view"];
controls the RESTful services
URL mapping
case "all":
// to handle REST Url /mobile/list/
$president_rest_handler = new PresidentRestHandler();

case "single":
// to handle REST Url /mobile/show/<id>/
$president_rest_handler = new PresidentRestHandler();
case "" :
//404 - not found;

RESTful base class

The class SimpleRest represents the RESTful service. It contains methods that are commonly used for RESTful service handlers. The getHttpStatusMessage() method is used to get the HTTP status message to build the response. The response contains the HTTP status code and message mapping array. It returns the appropriate header response message after receiving a status code. If the invalid status code is passed to this function or no such code is found in the mapping array, then the “Invalid Server Error” will be returned in the response.

The following is the code for SimpleRest.php

A simple RESTful webservices base class
Use this as a template and build upon it
class SimpleRest {

private $http_version = "HTTP/1.1";
public function setHttpHeaders($content_type, $status_code){

$status_msg = $this -> getHttpstatus_msg($status_code);

header($this->http_version. " ". $status_code ." ". $status_msg);
header("Content-Type:". $content_type);

public function getHttpstatus_msg($status_code){
$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[$status_code]) ? $httpStatus[$status_code] : $status[500];

The RESTful web service handler

This handles the REST request dispatched from the controller. PresidentRestHandler.php represents our RESTful web service handler. The service handler returns JSON data to the REST client. A status code needs to be returned to the client alongside the response data. On success, the status code will be 200. Other available should be used accordingly to set the response header.

The following is the code for PresidentRestHandler.php


class PresidentRestHandler extends SimpleRest {
function getAllPresidents() {
$president = new President();
$raw_data = $president->getAllPresidents();
if(empty($raw_data)) {
$status_code = 404;
$raw_data = array('error' => 'No presidents found!');
} else {
$status_code = 200;

$res = $this->encode_json($raw_data);
echo $res;

public function encode_html($res_data) {

$html_res = "<table border='1'>";
foreach($res_data as $key=>$value) {
    $html_res .= "<tr><td>". $key. "</td><td>". $value. "</td></tr>";
$html_res .= "</table>";
return $html_res;

public function encode_json($res_data) {
$json_res = json_encode($res_data);
return $json_res;

public function encode_xml($res_data) {
// creating object of SimpleXMLElement
$xml = new SimpleXMLElement('<?xml version="1.0"?><president></president>');
foreach($res_data as $key=>$value) {
$xml->addChild($key, $value);
return $xml->asXML();

public function getPresident($id) {
$president = new President();
$raw_data = $president->getPresident($id);
if(empty($raw_data)) {
$status_code = 404;
$raw_data = array('error' => 'No presidents found!');
} else {
$status_code = 200;
$res = $this->encode_json($raw_data);
    echo $res;


RESTful web service client

There are many stand-alone REST clients available to test or RESTful API.  You can use the postman app. You can also use a Google Chrome extension such as Advanced Rest Client extension to test the RESTful web service.  I used the Google Chrome extension to the RESTful API.

The following is the output of our PHP RESTful API:

The above picture shows the six presidents. This is when a request is made to http://localhost/rest/president/list/

The above picture shows the name of one president. This is when a request is made to http://localhost/rest/president/list/2/


In this tutorial, we have learnt how to build a REST API in PHP. We have used core PHP though there are frameworks for developing RESTful APIs in PHP. You can download the code here and use it to build your projects.

Thanks for the time and happy coding.

Was this article helpful?
Donate with PayPal:

Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.