PHPackages                             higimo/php-rest-service - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. higimo/php-rest-service

AbandonedArchivedLibrary[HTTP &amp; Networking](/categories/http)

higimo/php-rest-service
=======================

PHPRestService is a simple and fast PHP class for server side RESTful APIs.

0.2.0(7y ago)012MITPHPPHP &gt;=5.6.0

Since Feb 22Pushed 7y ago2 watchersCompare

[ Source](https://github.com/higimo/php-rest-service)[ Packagist](https://packagist.org/packages/higimo/php-rest-service)[ Docs](https://github.com/higimo/php-rest-service)[ RSS](/packages/higimo-php-rest-service/feed)WikiDiscussions master Synced today

READMEChangelog (1)DependenciesVersions (10)Used By (0)

php-rest-service
================

[](#php-rest-service)

Php-Rest-Service is a simple and fast PHP class for RESTful JSON APIs.

[![Build Status](https://camo.githubusercontent.com/6e002d7e77a975d2e864f33117056595b4cd953c1986cf484a5a3c8697131ed8/68747470733a2f2f7472617669732d63692e6f72672f6d6172636a2f7068702d726573742d736572766963652e706e67)](https://travis-ci.org/marcj/php-rest-service)

Features
--------

[](#features)

- Easy to use syntax
- Regular Expression support
- Error handling through PHP Exceptions
- Parameter validation through PHP function signature
- Can return a summary of all routes or one route through `OPTIONS` method based on PHPDoc (if `OPTIONS` is not overridden)
- Support of `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD` and `OPTIONS`
- Suppress the HTTP status code with ?\_suppress\_status\_code=1 (for clients that have troubles with that)
- Supports ?\_method=`httpMethod` as addition to the actual HTTP method.
- With auto-generation through PHP's `reflection`

Installation
------------

[](#installation)

- .
- More information available under .

Create a `composer.json`:

```
{
    "require": {
        "marcj/php-rest-service": "*"
    }
}
```

and run

```
$ wget http://getcomposer.org/composer.phar
$ php composer.phar install
```

After the installation, you need to include the `vendor/autoload.php` to make the class in your script available.

```
include 'vendor/autoload.php';
```

Requirements
============

[](#requirements)

- PHP 5.3 and above.
- PHPUnit to execute the test suite.
- Setup PATH\_INFO in mod\_rewrite (.htaccess) or other webserver configuration

Example config: apache webserver
--------------------------------

[](#example-configapache-webserver)

```
#.htaccess
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+) index.php/$1 [L,QSA]

```

nginx webserver
---------------

[](#nginx-webserver)

```
// edit virtualhost /etc/nginx/conf.d/name_virtualhost_file
server {
 .. something params ...
 location / {
  include fastcgi_params;

  fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_param SCRIPT_FILENAME $document_root/index.php;
 }
}

// and add line to /etc/nginx/fastcgi_params
fastcgi_param PATH_INFO $fastcgi_script_name;

```

Usage Demo
----------

[](#usage-demo)

### Way 1. The dirty &amp; fast

[](#way-1-the-dirty--fast)

```
use RestService\Server;

Server::create('/')
    ->addGetRoute('test', function(){
        return 'Yay!';
    })
    ->addGetRoute('foo/(.*)', function($bar){
        return $bar;
    })
    ->addPostRoute('foo', function($field1, $field2) {
      // do stuff with $field1, $field2 etc
      // or you can directly get them with $_POST['field1']
    })
->run();
```

### Way 2. Auto-Collection

[](#way-2-auto-collection)

`index.php`:

```
use RestService\Server;

Server::create('/admin', 'myRestApi\Admin')
    ->collectRoutes()
->run();
```

`MyRestApi/Admin.php`:

```
namespace MyRestApi;

class Admin {

    /**
    * Checks if a user is logged in.
    *
    * @return boolean
    */
    public function getLoggedIn(){
        return $this->getContainer('auth')->isLoggedIn();
    }

    /**
    * @param string $username
    * @param string $password
    * return boolean
    */
    public function postLogin($username, $password){
        return $this->getContainer('auth')->doLogin($username, $password);
    }

    /**
     * @param string $server
     * @url stats/([0-9]+)
     * @url stats
     * @return string
     */
    public function getStats($server = '1'){
        return $this->getServerStats($server);
    }

}
```

Generates following entry points:

```
    + GET  /admin/logged-in
    + POST /admin/login?username=&password=
    + GET  /admin/stats/([0-9]+)
    + GET  /admin/stats

```

### Way 3. Custom rules with controller

[](#way-3-custom-rules-with-controller)

`index.php`:

```
use RestService\Server;

Server::create('/admin', new MyRestApi\Admin) //base entry points `/admin`
    ->setDebugMode(true) //prints the debug trace, line number and file if a exception has been thrown.

    ->addGetRoute('login', 'doLogin') // => /admin/login
    ->addGetRoute('logout', 'doLogout') // => /admin/logout

    ->addGetRoute('page', 'getPages')
    ->addPutRoute('page', 'addPage')
    ->addGetRoute('page/([0-9]+)', 'getPage')
    ->addDeleteRoute('page/([0-9]+)', 'deletePage')
    ->addPostRoute('page/([0-9]+)', 'updatePage')

    ->addGetRoute('foo/bar/too', 'doFooBar')

    ->addSubController('tools', \RestApi\Tools) //adds a new sub entry point 'tools' => admin/tools
        ->addDeleteRoute('cache', 'clearCache')
        ->addGetRoute('rebuild-index', 'rebuildIndex')
    ->done()

->run();
```

`MyRestApi/Admin.php`:

```
namespace MyRestApi;

class Admin {
    public function login($username, $password){

        if (!$this->validLogin($username, $password))
            throw new InvalidLoginException('Login is invalid or no access.');

        return $this->getToken();

    }

    public function logout(){

        if (!$this->hasSession()){
            throw new NoCurrentSessionException('There is no current session.');
        }

        return $this->killSession();

    }

    public function getPage($id){
        //...
    }
}

namespace RestAPI;

class Tools {
    /**
    * Clears the cache of the app.
    *
    * @param boolean $withIndex If true, it clears the search index too.
    * @return boolean True if the cache has been cleared.
    */
    public function clearCache($withIndex = false){
        return true;
    }
}
```

Responses
---------

[](#responses)

The response body is always a array (JSON per default) containing a status code and the actual data. If a exception has been thrown, it contains the status 500, the exception class name as error and the message as message.

Some examples:

```
+ GET admin/login?username=foo&password=bar
  =>
  {
     "status": "200",
     "data": true
  }

+ GET admin/login?username=foo&password=invalidPassword
  =>
  {
     "status": "500",
     "error": "InvalidLoginException",
     "message": "Login is invalid or no access"
  }

+ GET admin/login
  =>
  {
     "status: "400",
     "error": "MissingRequiredArgumentException",
     "message": "Argument 'username' is missing"
  }

+ GET admin/login?username=foo&password=invalidPassword
  With active debugMode we'll get:
  =>
  {
     "status": "500",
     "error": "InvalidLoginException",
     "message": "Login is invalid or no access",
     "line": 10,
     "file": "libs/RestAPI/Admin.class.php",
     "trace":
  }

+ GET admin/tools/cache
  =>
  {
     "status": 200,
     "data": true
  }

```

License
-------

[](#license)

Licensed under the MIT License. See the LICENSE file for more details.

Take a look into the code, to get more information about the possibilities. It's well documented.

[![Bitdeli Badge](https://camo.githubusercontent.com/b2e837e667faec70e119296f4a9bb567287e2e3eeb9620c7c1efbbe6211b6f2f/68747470733a2f2f64327765637a68766c38323376302e636c6f756466726f6e742e6e65742f6d6172636a2f7068702d726573742d736572766963652f7472656e642e706e67)](https://bitdeli.com/free "Bitdeli Badge")

###  Health Score

25

—

LowBetter than 40% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor3

3 contributors hold 50%+ of commits

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.

###  Release Activity

Cadence

Every ~275 days

Recently: every ~498 days

Total

9

Last Release

2574d ago

PHP version history (2 changes)0.1.0PHP &gt;=5.3.0

0.2.0PHP &gt;=5.6.0

### Community

Maintainers

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

---

Top Contributors

[![higimo](https://avatars.githubusercontent.com/u/2804205?v=4)](https://github.com/higimo "higimo (5 commits)")[![marcj](https://avatars.githubusercontent.com/u/450980?v=4)](https://github.com/marcj "marcj (4 commits)")[![ntvsx193](https://avatars.githubusercontent.com/u/2971095?v=4)](https://github.com/ntvsx193 "ntvsx193 (3 commits)")[![urkle](https://avatars.githubusercontent.com/u/101123?v=4)](https://github.com/urkle "urkle (2 commits)")[![freinn](https://avatars.githubusercontent.com/u/2404609?v=4)](https://github.com/freinn "freinn (2 commits)")[![mamartel](https://avatars.githubusercontent.com/u/1738891?v=4)](https://github.com/mamartel "mamartel (1 commits)")[![DeyV](https://avatars.githubusercontent.com/u/311626?v=4)](https://github.com/DeyV "DeyV (1 commits)")[![bitdeli-chef](https://avatars.githubusercontent.com/u/3092978?v=4)](https://github.com/bitdeli-chef "bitdeli-chef (1 commits)")[![olect](https://avatars.githubusercontent.com/u/1047183?v=4)](https://github.com/olect "olect (1 commits)")

---

Tags

phpapirestrestful

### Embed Badge

![Health badge](/badges/higimo-php-rest-service/health.svg)

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

###  Alternatives

[arhitector/yandex

PHP SDK для работы с некоторыми сервисами яндекса (Яндекс.Диск, Yandex.Disk)

13082.0k5](/packages/arhitector-yandex)[ismaeltoe/osms

PHP library wrapper of the Orange SMS API.

4639.8k](/packages/ismaeltoe-osms)

PHPackages © 2026

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