PHPackages                             dking3876/simple-rest-api - 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. dking3876/simple-rest-api

ActiveLibrary[API Development](/categories/api)

dking3876/simple-rest-api
=========================

A Restful api

1.1.0(8y ago)01.4kMITPHP

Since Sep 21Pushed 4y ago1 watchersCompare

[ Source](https://github.com/dking3876/SimpleRESTAPI)[ Packagist](https://packagist.org/packages/dking3876/simple-rest-api)[ RSS](/packages/dking3876-simple-rest-api/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (1)Dependencies (2)Versions (12)Used By (0)

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

[](#installation)

`composer require dking3876/simple-rest-api`

### Setup

[](#setup)

An htaccess file should be set up to ensure CORS is enabled. The below is an example of a usuable configuration

```

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Origin, Content-Type, X-Auth-Token , Authorization, x-requested-with"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

```

### Configuration

[](#configuration)

in your main file you can set up your configuration as an array and pass that array to the API constructor.

```
$api = new SimpleRESTAPI\API($config);
```

The configuration array has the following indexes

- connection: For holding database credentials
- base: for setting a base path for your api allowing the use of versioning for different endpoints
- response: type of default response heade
- socket: for use with websockets
- paths: an array of url paths, request methods and responses

#### Connection:

[](#connection)

Simple REst api can help hold credentials for connection to database. These credentials can than be accessed as static properties `\SimpleRESTAPI\API::$DBCreds->{host|port|database|username|password}`

```
$config = array(
    "connection" => array(
        "host"  => "localhost",
        "port"  => "",
        "database"  => "",
        "username"  => "",
        "password"  => ""
    )
);
```

#### Base

[](#base)

This is the starting base path for the api. This path is used to help version your api.

```
$config = array(
    "base"  => "/api/v2/"
);
```

#### Response

[](#response)

The default response header for all requests. You can override this by ....

```
$config = array(
    "response"  => 'Content-Type: application/json'
);
```

#### Socket

[](#socket)

SimpleRESTAPI comes with a built in websocket. You can set a callable method for the following events

- onOpen: fires when a client makes a connection. A reference to the socketClass and the clientID used for the duration of the client session are passed as arguments. `(\SimpleRESTAPI\WebSocket $socket, $clientId)`
- onMessage: fires when a client sends a new message. A reference to the socketClass, the clientId sending the message, the message data, and the length of the message are passed as arguments. `(\SimpleRESTAPI\WebSocket $socket, $clientId, $data, $dataLength)`
- onTick: fires for each connected client, for each loop/tick (a tick is apx 8-12 seconds). A reference to the socketClass and the clientID for the current 'tick' are passed as arguments. `(\SimpleRESTAPI\WebSocket $socket, $clientId)`
- onClose: Fires when a client disconnects from the service. A reference to the socketClass, the clientId disconnecting, and the disconnect status are passed as arguments. `(\SimpleRESTAPI\WebSocket $socket, $clientId, $status)`

```
$sample = function(\SimpleRESTAPI\WebSocket $socket, $clientId, $status){

}
$config = array(
    "socket"    => [
        "host"  => "127.0.0.1",
        "port"  => "9002",
        "events"    => [
            "onOpen"  =>array('Test\\testing\\test_socket_controller', 'testOpen'),
            "onMessage"   => 'Test\\testing\\test_socket_controller::testMessage',
            "onTick"    => function(\SimpleRESTAPI\WebSocket $socket, $clientId){

            },
            "onClose"     => $sample
        ]
    ]
);
```

#### Paths

[](#paths)

Paths are an array of path arrays defined to know how to route the request. A path definition consists of:

- path: the defined path using regex. Some examples are provided below

    ```
          'path'  => '^projects/?$`
          'path' => '^projects/(?P[^/]*)/?$`

    ```

    You can define paths using [named subpatterns for path regex definitions](https://www.regular-expressions.info/named.html)
- Request Method and callable function: This defintion provideds the function to call for the matchedd request method. The callable can be any of the following examples.

    ```
          'GET'       => function($params, $tokens){}
          'HEAD'      => $myNamedFunction
          'POST'      => 'MyNameSpace\\MyClass::$myStaticMethod'
          'PATCH'     => array('MyNameSpace\MyClass', 'myMethod')
          'PUT'       => array($myInstantiatedObject, 'myMethod')
          'DELETE'    => ($params, $tokens)=>{}

    ```

An array of GET,POST parameters is passed as the first argument to your function. An array of url Tokens ((?P&lt;project\_id&gt;\[^/\]\*) would equate to $tokens\['project\_id'\])

### Main Script

[](#main-script)

Once you have set up your configuration array simply pass the configuration as the argument for the constructor of the api.

```
$config = [
    'connection'    => ...
    ...
    'paths' => array(...)
]
$loader = require __DIR__.'/../vendor/autoload.php';
$api = new SimpleRESTAPI\API($config);

$api->router();
echo json_encode($api->response()); //used to encode the response to json.
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity70

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~11 days

Total

7

Last Release

3089d ago

### Community

Maintainers

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

---

Top Contributors

[![dking3876](https://avatars.githubusercontent.com/u/10117938?v=4)](https://github.com/dking3876 "dking3876 (23 commits)")

---

Tags

api

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dking3876-simple-rest-api/health.svg)

```
[![Health](https://phpackages.com/badges/dking3876-simple-rest-api/health.svg)](https://phpackages.com/packages/dking3876-simple-rest-api)
```

###  Alternatives

[m165437/laravel-blueprint-docs

API Blueprint Renderer for Laravel

22779.0k](/packages/m165437-laravel-blueprint-docs)

PHPackages © 2026

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