2017 © Pedro Peláez

library restserver

Simple and organized Restful web services



Simple and organized Restful web services

  • Sunday, July 28, 2013
  • by diogok
  • Repository
  • 4 Watchers
  • 32 Stars
  • 10,385 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 12 Forks
  • 2 Open issues
  • 1 Versions
  • 9 % Grown



RestServer is a PHP library/framework for building RESTful webservices and also websites., (*1)

It allows you to route Method,URI and MIME-TYPE to specific Resources handlers, access the Requested data and provide a proper Response., (*2)

Here it's decribe its documentation, together with the example folder and tests for reference., (*3)

This version is based on the namespaces branch of Xavier., (*4)


The simplest way is using composer, just declare the restserver dependency in you composer.json:, (*5)

        "restserver/restserver": "*"

If not using composer, you can use the restserver.phar: just download and require it in your application., (*6)

Checkout the api documentation., (*7)

The Server

The first step to defining you REST service is to instantiate the server, as follows:, (*8)

$rest = new Rest\Server

This way the server will grab the requested URI to work with, or you can specify a URI if you are not working with UrlRewrite., (*9)

For example, if the resource to load is coming from $_GET["q"]:, (*10)

$rest = new Rest\Serve($_GET['q']);

This way restserver will treat $_GET['q'] as the requested URI., (*11)

Creating resources

This is the main funcionality of this package, is to define the available resources., (*12)


Dissecating this, you get a METHOD, a URI and an ACTION. Any method is available, even custom ones. URIs can be any URI and it support variable parameters, as follow:, (*13)


Will give you a map to the "id" parameter (more on this later)., (*14)

On action, it can be a Rest\Controller, a Rest\View, a method within any of these or a anonymous function, as such:, (*15)

$rest->addMap("GET","/uri",function($rest) {
        return $rest;

You can also map specific mime types to be accessible, according to the requested "accepts":, (*16)


After setting the resources, you must execute the server:, (*17)

echo $rest->execute();

This will trigger the server to work., (*18)

More on resources handling on future topics., (*19)

Global utilities

The server have a few utilities to deal with the global server scope., (*20)

You can set variables to be acessible at any rest resource as follow:, (*21)

$key = $rest->getParamter("key");

You can also get all setted parameters with:, (*22)

$params = $rest->getParameters();

You can set global accepted mime-types:, (*23)


You can dinamically set/get the requested URI:, (*24)


The usage is very simple, first you'll need to include either the "phar" or the initial Rest/Server.php class., (*25)

include 'restserver.phar'
$api = new Rest\Server();
// more logic to come here.

You can instantiate the Rest\Server to start handling the requests, it will get the URI from the HTTP Request, but you can also provide a custom one for the Rest\Server($url) constructor., (*26)

After configuring the server you call the "execute" method so it can chain the request/response cicle., (*27)


Most of work is mapping URIs to functions or controllers., (*28)

You can map any method (even custom) and URI to a lambda/closure function or to a Controller class (that implements Rest\Controller) or a specific method of a controller., (*29)


The URI parameter accepts any regex, and also name parameters (:name or :?name for optional parameter), and an array of accepted mime types., (*30)

Controllers and Views

(Also apply to lambda/closure), (*31)

All controllers to be mapped must implement Rest\Controller, it implies in implementing a single default method as follow and a public constructor with no arguments(or optional arguments):, (*32)

    class MyController implements Rest\Controller {
        public function execute($rest) {

Other method that might get mapped into the server must also receive this one parameter., (*33)

This method parameter is an instance of the Rest\Server from where you can get the request details, data and response., (*34)

The methods can return the rest server, to end the cycle, or another Controller or View to follow the request to., (*35)

    class MyController implements Rest\Controller {
        public function execute($rest) {
            return new MyViewOrOtherController($anyDataOrNot); //will foward the request

The same apply to Views, but implements Rest\View., (*36)

Default Controllers and Views

The Rest\Server comes with some default Controller and Views for most common use cases., (*37)

  • Rest\Controller\BadRequest
  • Rest\Controller\Created
  • Rest\Controller\Forbidden
  • Rest\Controller\InternalServerError
  • Rest\Controller\MethodNotAllowed
  • Rest\Controller\MovedPermanently($newLocation)
  • Rest\Controller\NotAcceptable
  • Rest\Controller\NotAuthorized
  • Rest\Controller\NotFound
  • Rest\Controller\NotModified
  • Rest\Controller\Redirect($newLocation)
  • Rest\View\Generic([$fileToRender,$data])
  • Rest\View\JSon($object)


RestServer support both BASIC and DIGEST http authentication mechanisms. You can access the Authenticator object as follow:, (*38)

$auth = $rest->getAuthenticator();

It will get the user/password provided on the request. For BASIC auth, you can get it simply:, (*39)

$user = $auth->getUser();
$pass = $auth->getPassword();

Or for Digest:, (*40)

    $user = $auth->getUser();
    // your logic to lookup user pass

You can them test or set the authentication status:, (*41)

    $ok = $auth->isAuthenticated();

If by "execute" time authentication fail, server will respond properly., (*42)


To deal with the request, withing a rest action, you can access it as follows:, (*43)

$req = $rest->getRequest();

The request contains the many thing the user may have sent to and requested from the server. Here are the options:, (*44)

$req->getGet(); // whole $_GET
$req->getFiles(); // from multipart/form-data POSTs
$req->getFiles($key); // from multipart/form-data POSTs
$req->getInput(); // from PUTs
$req->getETag(); // The 'if-match', good for your caching
$req->getParameter($ket); // from the resource configured URI
$req->getURI(); // the requested URI
$req->getURI($i); // the "part" of the URI (count each "/")
$req->getExtension(); // the extension of the URI
$ok = $req->acceptMime("mime/type"); // If mime is acceptable

And that's what you get., (*45)


With the response object, you can set what to return for the user., (*46)

$res = $rest->getResponse();

And here are it's methods:, (*47)

$res->addHeader("Content-Type: application/json");
$res->cleanHeader(); // undo headers
$res->setResponse($content); // body of the response
$res->sendResponse($content); // sends partial response already, better for big ones
$res->cleanResponse($content); // clean setted response texts

The response will be sent to client at the end of the restserver executing cycle., (*48)

Controllers and Views

Controllers and views are the default option for action on a request. A controller or view to be used on RestServer must implement the Rest\Controller or Rest\View interface, which require a single public method:, (*49)

class MyController implements \Rest\Controller {
    public function execute(\Rest\Server $rest) {
        // your logic here
        return $rest;

The execute method (or any other method to be used in restserver) will receive the RestServer object and must return the same restserver, to end the request, or another action(controller or view) to forward the request control to., (*50)

class MyController implements \Rest\Controller {
    public function execute(\Rest\Server $rest) {
        $rest->getResponse()->setResponse("Hello, world!");
        return $rest;

    public function other(\Rest\Server $rest) {
        return new MyView();


The package comes with a few controller and a view implementation for generic usage, as follow:, (*51)

new \Rest\Controller\BadRequest;
new \Rest\Controller\Created;
new \Rest\Controller\Fobidden;
new \Rest\Controller\InternalServerError;
new \Rest\Controller\MethodNotAllowed;
new \Rest\Controller\MovedPermanently($newLocation);
new \Rest\Controller\NotAcceptable;
new \Rest\Controller\NotAuthorized;
new \Rest\Controller\NotFound;
new \Rest\Controller\NotModified;
new \Rest\Controller\Redirect($location);

new \Rest\View\Generic($template_path,$data);
new \Rest\View\JSon($data);

Lot's of these controllers are used automatically, like NotFound, MethodNotAllowed and a few others., (*52)

Anonymous functions

The server can also use anonymous functions to deal with the resources, work the same way as the execute method of a generic controller (that's is what happens)., (*53)

$rest->addMap("GET","/users",function($rest) {
        // your logic
        return $rest; // or return new \Rest\View\JSON($data) for example

E-Tags and Cache

A simple new feature is to deal with e-tags for caching, a common case would be:, (*54)

$rest->addMap("GET","/user/:uid",function($rest) {
    $id = $rest->getREquest()->getParameter("uid");
    $etag = $rest->getREquest()->getEtag();
    // check if etag is still same data, could be a md5 of user data or something
    if($same) {
        return new \Rest\Controller\NotModified;
    } else {
        return new \Rest\View\JSon($user);

Mime-Type handling

RestServer can route and respond properly for requests of different mime-types., (*55)

You can define mimes to accept both globally or by resources, as follows:, (*56)


In such situation, the first resource would respond only to application/json requests (accept-mime header), the second only to text/html and the rest to anything or text/html., (*57)

Full Example

A full example can be found on source-code folder "example", and is very complete on resource usage and heavily commented and tested., (*58)

The tests and the example tests also can be used as a resource for information too., (*59)

More on REST

Soon., (*60)


Distributed under the Eclipse Public License., (*61)

The Versions

28/07 2013


9999999-dev http://github.com/diogok/restserver

Simple and organized Restful web services

  Sources   Download


The Requires

  • php >=5.3.0


rest http