PHPackages                             doubotis/php-rest-wrapper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. doubotis/php-rest-wrapper

ActiveLibrary[API Development](/categories/api)

doubotis/php-rest-wrapper
=========================

A REST Wrapper for PHP

0141PHP

Since Sep 23Pushed 6y ago1 watchersCompare

[ Source](https://github.com/doubotis/php-rest-wrapper)[ Packagist](https://packagist.org/packages/doubotis/php-rest-wrapper)[ RSS](/packages/doubotis-php-rest-wrapper/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependenciesVersions (1)Used By (0)

php-rest-wrapper
================

[](#php-rest-wrapper)

PHP Wrapper for managing easy Rest-based APIs

Main features
-------------

[](#main-features)

Some main features this PHP wrapper have :

- Code of all requests are separated by files
- Using reflexion to make coding easier
- Handle XML and JSON responses. You use arrays, the Wrapper does the conversion.

How to install
--------------

[](#how-to-install)

Add the library in your composer.json file :

```
require {
    "doubotis/php-rest-wrapper": "dev-master"
}

```

How to use
----------

[](#how-to-use)

### Full example

[](#full-example)

```
// Get the REQUEST_URI.
$requestURI = $_SERVER['REQUEST_URI'];

// Build an API Request and pass the REQUEST_URI var.
$request = new Doubotis\PHPRestWrapper\APIRequest($requestURI);

// Build the dispatcher, that will help to use the right implementation method.
// For production purposes, it's better to store it into $GLOBALS.
$dispatcher = new Doubotis\PHPRestWrapper\Dispatchers\APIFileResourceDispatcher(__DIR__ . "/resource.txt");

// Get a handler and pass a dispatcher to make the handle.
$handler = new Doubotis\PHPRestWrapper\APIResponseHandler($dispatcher);

// Ask the handle to get the response.
$response = null;
try {
    $handler->handleRequest($request);
    $response = $handler->getResponse();
} catch (Exception $ex) {
    die($ex->getMessage());
}

// Prints the result.
if (is_a($response, Doubotis\PHPRestWrapper\APIStructuredResponse::class)) {
    if ($request->getExtension() == "json") {
        header('Content-Type: text/json');
        echo $response->asJSON();
    } else if ($request->getExtension() == "xml") {
        header('Content-Type: text/xml');
        echo $response->asXML();
    }
}
```

### APIRequest

[](#apirequest)

You can build an APIRequest object from the `$_SERVER['REQUEST_URI']` var. From that, you can get:

- the complete URI
- the HTTP method
- the resource
- the extension
- the filter
- the sorting
- the HTTP Headers

### Dispatchers

[](#dispatchers)

You can choose an implementation of dispatcher you want to use.

#### Using `APIFileResourceDispatcher`

[](#using-apifileresourcedispatcher)

This dispatcher allows you to define, from a txt file, which implementation classes you want to use, associated with a regex. Here is an exemple of this txt file:

```
GET Base /
GET POST Users /users
GET POST DELETE User /users/([^/]+)
GET POST Me /me
GET POST MeItIs /me/itis

```

#### Using `APIAnnotationDispatcher`

[](#using-apiannotationdispatcher)

If all your implementation classes are packed into a single directory, you can use this one, and define the method `getPath()` for each implementation class, that will be used to find the right class to use. The `getPath()` method must return a regex.

#### Implementing a custom dispatcher and using it

[](#implementing-a-custom-dispatcher-and-using-it)

You can define a new class that extends `APIBaseDispatcher`, and customize the `getClassForRequest($request)` method, to fullfill your requirements.

### Implementation Class

[](#implementation-class)

For above example, let's see the `GET Base /` line. Create a `Base` class extending `NativeImplementation` implementing `IGetHandler` because this is the only supported method. Next, override the get method, like that :

```
public function get($request)
{
    $arr = array(
        "version" => 10000,
        "compilationDate" => time()
    );

    return new Doubotis\PHPRestWrapper\Responses\APIStructuredResponse($arr);
}
```

Additionnaly, if you want to open DB connections or files, you can override `init()` and `dealloc()` methods.

### Response

[](#response)

After asking to handle the request, you can get the response, inherited from `APIResponse`. This object is returned from any implementation class.

```
$handler->handleRequest($request);
$response = $handler->getResponse();
```

#### Response type `APIStructuredResponse`

[](#response-type-apistructuredresponse)

This implementation of `APIResponse` allows you to store full objects in a dictionary, and returns them as JSON or XML.

```
echo $response->asJSON();
echo $response->asXML();
```

#### Response type `APIBinaryResponse`

[](#response-type-apibinaryresponse)

This implementation could be used to return any binary data, like images, PDF, etc. If you want to return specifically a PNG image, you can use the response type `APIImageResponse` :

```
echo $response->asPNG();
```

### Throwing exceptions

[](#throwing-exceptions)

If something goes wrong into the process, you can throw many exceptions :

- BadRequestException : means parameters of this resource are missing or wrong.
- ForbiddenAccessException : the access to this resource is forbidden.
- InternalErrorException : the server encountered an internal error.
- HTTPException : the base exception class.
- NotImplementedException : the resource is not implemented yet.
- ResourceNotFoundException : the resource cannot be found. Useful when using regex for asking a specific username for instance.
- TooManyRequestsException : the resource cannot be accessed because the user have done too many requests.
- UnauthorizedAccessException : the resource is not authorized, but can be authorized by specifying some details.
- UnavailableServiceException : the resource is not available.

Each of these exceptions handle the status HTTP code and wrap the stack exception to allow external users to debug what is wrong. You can add a detailed description of the exception by using the `setMessage()` method.

By specifying the header `X-Show-Stacktrace` any user can see the entire stack exception. You can of course limit the use of this header to specific users.

###  Health Score

19

—

LowBetter than 10% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/d7238cd3193dddcef881f5df072e3c2974fa61e76292ba4ea63bdf788d992f13?d=identicon)[Doubotis](/maintainers/Doubotis)

---

Top Contributors

[![doubotis](https://avatars.githubusercontent.com/u/6214768?v=4)](https://github.com/doubotis "doubotis (35 commits)")

### Embed Badge

![Health badge](/badges/doubotis-php-rest-wrapper/health.svg)

```
[![Health](https://phpackages.com/badges/doubotis-php-rest-wrapper/health.svg)](https://phpackages.com/packages/doubotis-php-rest-wrapper)
```

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M480](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M272](/packages/twilio-sdk)[knplabs/github-api

GitHub API v3 client

2.2k15.8M187](/packages/knplabs-github-api)[facebook/php-business-sdk

PHP SDK for Facebook Business

90121.9M34](/packages/facebook-php-business-sdk)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

73813.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

263103.1M454](/packages/google-gax)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
