PHPackages                             inbo/codeigniter-rest - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. inbo/codeigniter-rest

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

inbo/codeigniter-rest
=====================

CodeIgniter 3 RESTful API Resource Base Controller

1.0.8(5y ago)338MITPHPPHP &gt;=5.4.0

Since Oct 29Pushed 5y ago1 watchersCompare

[ Source](https://github.com/Nader-abdi/codeigniter-rest)[ Packagist](https://packagist.org/packages/inbo/codeigniter-rest)[ Docs](https://inbo.ir)[ RSS](/packages/inbo-codeigniter-rest/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (10)Used By (0)

 [ ![](https://camo.githubusercontent.com/5b8d9090a678d487fbff6d0d7400659c2180a80374753a34de65cc380c2e2dca/68747470733a2f2f636f646569676e697465722e636f6d2f6173736574732f696d616765732f63692d6c6f676f2d6269672e706e67) ](https://codeigniter.com/)

CodeIgniter RESTful API
=======================

[](#codeigniter-restful-api)

CodeIgniter 3 RESTful API Resource Base Controller

[![Latest Stable Version](https://camo.githubusercontent.com/6d687d7ebf7153a258002400a4347f1ac053d010b8d1e600a6ba24152c86f99b/68747470733a2f2f706f7365722e707567782e6f72672f79696461732f636f646569676e697465722d726573742f762f737461626c653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/yidas/codeigniter-rest)[![Latest Unstable Version](https://camo.githubusercontent.com/ef716744862255be326e5f47e112a17921ef25117d39e10c51bb6ec2bf0c00a5/68747470733a2f2f706f7365722e707567782e6f72672f79696461732f636f646569676e697465722d726573742f762f756e737461626c653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/yidas/codeigniter-rest)[![License](https://camo.githubusercontent.com/909fc02ac625f9a847d9a87de4a7e15878372aab324dd2238dfcab6cfb8d62cf/68747470733a2f2f706f7365722e707567782e6f72672f79696461732f636f646569676e697465722d726573742f6c6963656e73653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/yidas/codeigniter-rest)

This RESTful API extension is collected into [yidas/codeigniter-pack](https://github.com/yidas/codeigniter-pack) which is a complete solution for Codeigniter framework.

Features
--------

[](#features)

- ***PSR-7** standardization*
- ***RESTful API** implementation*
- ***Laravel Resource Controllers** pattern like*

---

OUTLINE
-------

[](#outline)

- [Demonstration](#demonstration)
    - [RESTful Create Callback](#restful-create-callback)
    - [Packed Standard Format](#packed-standard-format)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
    - [Routes Setting](#routes-setting)
- [Resource Controllers](#resource-controllers)
    - [Build Methods](#build-methods)
    - [Custom Routes &amp; Methods](#custom-routes--methods)
    - [Behaviors](#behaviors)
    - [Usage](#usage)
- [HTTP Request](#http-request)
    - [Usage](#usage-1)
- [HTTP Response](#http-response)
    - [Usage](#usage-2)
- [Reference](#reference)

---

DEMONSTRATION
-------------

[](#demonstration)

```
class ApiController extends yidas\rest\Controller
{
    public function index()
    {
        return $this->response->json(['bar'=>'foo']);
    }
}
```

Output with status `200 OK`:

```
{"bar":"foo"}
```

### RESTful Create Callback

[](#restful-create-callback)

```
public function store($requestData=null) {

    $this->db->insert('mytable', $requestData);
    $id = $this->db->insert_id();

    return $this->response->json(['id'=>$id], 201);
}
```

Output with status `201 Created`:

```
{"id":1}
```

### Packed Standard Format

[](#packed-standard-format)

```
try {
    throw new Exception("API forbidden", 403);
} catch (\Exception $e) {
    // Pack data into a standard format
    $data = $this->pack(['bar'=>'foo'], $e->getCode(), $e->getMessage());
    return $this->response->json($data, $e->getCode());
}
```

Output with status `403 Forbidden`:

```
{"code":403,"message":"API forbidden","data":{"bar":"foo"}}
```

---

REQUIREMENTS
------------

[](#requirements)

This library requires the following:

- PHP 5.4.0+
- CodeIgniter 3.0.0+

---

INSTALLATION
------------

[](#installation)

Run Composer in your Codeigniter project under the folder `\application`:

```
composer require yidas/codeigniter-rest

```

Check Codeigniter `application/config/config.php`:

```
$config['composer_autoload'] = TRUE;
```

> You could customize the vendor path into `$config['composer_autoload']`

---

CONFIGURATION
-------------

[](#configuration)

1. Create a controller to extend `yidas\rest\Controller`,

```
class Resource extends yidas\rest\Controller {}
```

2. Add and implement action methods referring by [Build Methods](#build-methods).

Then you could access RESTful API:

```
https://yourname.com/resource/api
https://yourname.com/resource/api/123

```

You could also use `/ajax` instead of `/api` if you like:

```
https://yourname.com/resource/ajax
https://yourname.com/resource/ajax/123

```

> `resource` is Controller name, if you don't want to have `/api` or `/ajax` in URI you could set Routes Setting as below.

### Routes Setting

[](#routes-setting)

If you want to have the standard RESTful URI pattern, which defines controller as resource for URI, for example:

```
https://yourname.com/resource
https://yourname.com/resource/123

```

You could add a pair of routes for this controller into `\application\config\routes.php` to enable RESTful API url:

```
$route['resource_name'] = '[Controller]/route';
$route['resource_name/(:num)'] = '[Controller]/route/$1';
```

---

RESOURCE CONTROLLERS
--------------------

[](#resource-controllers)

The base RESTful API controller is `yidas\rest\Controller`, the following table is the actions handled by resource controller, the `action` refers to `CI_Controller`'s action name which you could override:

HTTP MethodURI (Routes Setting)ActionDescriptionGET/photosindexList the collection's members.POST/photosstoreCreate a new entry in the collection.GET/photos/{photo}showRetrieve an addressed member of the collection.PUT/PATCH/photos/{photo}updateUpdate the addressed member of the collection.PUT/photosupdateUpdate the entire collection.DELETE/photos/{photo}deleteDelete the addressed member of the collection.DELETE/photosdeleteDelete the entire collection.> Without Routes Setting, the URI is like `/photos/api` &amp; `/photos/api/{photo}`.

### Build Methods:

[](#build-methods)

You could make a resource controller by referring the [Template of Resource Controller](https://github.com/yidas/codeigniter-rest/blob/dev/examples/RestController.php).

The following RESTful controller methods could be add by your need. which each method refers to the action of Resource Controller table by default, and injects required arguments:

```
public function index() {}
protected function store($requestData=null) {}
protected function show($resourceID) {}
protected function update($resourceID=null, $requestData=null) {}
protected function delete($resourceID=null, $requestData=null) {}
```

> `$resourceID` (string) is the addressed identity of the resource from request
>
> `$requestData` (array) is the array input data parsed from request raw body, which supports `x-www-form-urlencoded` request content type. (Alternatively, use [`this->request->getRawBody()`](#getrawbody) to get raw data)

### Custom Routes &amp; Methods

[](#custom-routes--methods)

The default routes for mapping the same action methods of Resource Controller are below:

```
protected $routes = [
    'index' => 'index',
    'store' => 'store',
    'show' => 'show',
    'update' => 'update',
    'delete' => 'delete',
];
```

You could override it to define your own routes while creating a resource controller:

```
class ApiController extends yidas\rest\Controller {

    protected $routes = [
        'index' => 'find',
        'store' => 'save',
        'show' => 'display',
        'update' => 'edit',
        'delete' => 'destory',
    ];
}
```

After reseting routes, each RESTful method (key) would enter into specified controller action (value). For above example, while access `/resources/api/` url with `GET` method would enter into `find()` action. However, the default route would enter into `index()` action.

> The keys refer to the actions of Resource Controller table, you must define all methods you need.

### Behaviors

[](#behaviors)

Resource Controller supports behaviors setting for each action, you could implement such as authentication for different permissions.

#### \_setBehavior()

[](#_setbehavior)

Set behavior to a action before route

```
protected boolean _setBehavior(string $action, callable $function)
```

*Example:*

```
class BaseRestController extends \yidas\rest\Controller
{
    function __construct()
    {
        parent::__construct();

        // Load your Auth library for verification
        $this->load->library('Auth');
        $this->auth->verify('read');

        // Set each action for own permission verification
        $this->_setBehavior('store', function() {
            $this->auth->verify('create');
        });
        $this->_setBehavior('update', function() {
            $this->auth->verify('update');
        });
        $this->_setBehavior('delete', function() {
            $this->auth->verify('delete');
        });
    }
    // ...
```

### Usage

[](#usage)

#### pack()

[](#pack)

Pack array data into body format

You could override this method for your application standard.

```
protected array pack(array|mixed $data, integer $statusCode=200, string $message=null)
```

*Example:*

```
$data = $this->pack(['bar'=>'foo'], 403, 'Forbidden');
return $this->response->json($data, 403);
```

JSON Result:

```
{
    "code": 403,
    "message": "Forbidden",
    "data": {
        "bar": "foo"
    }
}

```

---

HTTP REQUEST
------------

[](#http-request)

The PSR-7 request component `yidas\http\request` is preloaded into `yidas\rest\Controller`, which provides input handler and HTTP Authentication. You could call it by `$this->request` in controller class.

### Usage

[](#usage-1)

#### getRawBody()

[](#getrawbody)

Returns the raw HTTP request body

```
public string getRawBody()
```

*Example:*

```
// Request with `application/json` raw
$data = json_decode($this->request->getRawBody);
```

#### getAuthCredentialsWithBasic()

[](#getauthcredentialswithbasic)

Get Credentials with HTTP Basic Authentication

```
public array getAuthCredentialsWithBasic()
```

*Example:*

```
list($username, $password) = $this->request->getAuthCredentialsWithBasic();
```

#### getAuthCredentialsWithBearer()

[](#getauthcredentialswithbearer)

Get Credentials with OAuth 2.0 Authorization Framework: Bearer Token Usage

```
public string getAuthCredentialsWithBearer()
```

*Example:*

```
$b64token = $this->request->getAuthCredentialsWithBearer();
```

---

HTTP RESPONSE
-------------

[](#http-response)

The PSR-7 response component `yidas\http\response` is preloaded into `yidas\rest\Controller`, which provides output handler and formatter. You could call it by `$this->response` in controller class.

### Usage

[](#usage-2)

#### json()

[](#json)

JSON output shortcut

```
public void json(array|mixed $data, integer $statusCode=null)
```

*Example:*

```
$this->response->json(['bar'=>'foo'], 201);
```

#### setFormat()

[](#setformat)

Set Response Format into CI\_Output

```
public self setFormat(string $format)
```

*Example:*

```
$this->response->setFormat(\yidas\http\Response::FORMAT_JSON);
```

#### setData()

[](#setdata)

Set Response Data into CI\_Output

```
public self setData(mixed $data)
```

*Example:*

```
$this->response->setData(['foo'=>'bar']);
```

#### send()

[](#send)

Sends the response to the client.

```
public void send()
```

*Example:*

```
$this->response->send();
```

#### withAddedHeader()

[](#withaddedheader)

Return an instance with the specified header appended with the given value.

```
public self withAddedHeader(string $name, string $value)
```

*Example:*

```
return $this->response
    ->withAddedHeader('Access-Control-Allow-Origin', '*')
    ->withAddedHeader('X-Frame-Options', 'deny')
    ->json(['bar'=>'foo']);
```

---

REFERENCE
---------

[](#reference)

- [HTTP authentication by MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication)
- [RFC7617 - The 'Basic' HTTP Authentication Scheme](https://tools.ietf.org/html/rfc7617)
- [RFC6750 - The OAuth 2.0 Authorization Framework: Bearer Token Usage](https://tools.ietf.org/html/rfc6750)
- [REST Relationship between URL and HTTP methods](https://en.wikipedia.org/wiki/Representational_state_transfer#Relationship_between_URI_and_HTTP_methods)
- [PSR-7: HTTP message interfaces](https://www.php-fig.org/psr/psr-7/)

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 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 ~21 days

Recently: every ~11 days

Total

9

Last Release

1853d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/507b2c0010d5f388785fe5d7294c837ca56eec84f3e7b2a670608272fec45b77?d=identicon)[AtaTurk1925](/maintainers/AtaTurk1925)

---

Top Contributors

[![Nader-abdi](https://avatars.githubusercontent.com/u/11696156?v=4)](https://github.com/Nader-abdi "Nader-abdi (9 commits)")

---

Tags

apicodeigniterauthorizationcontroller

### Embed Badge

![Health badge](/badges/inbo-codeigniter-rest/health.svg)

```
[![Health](https://phpackages.com/badges/inbo-codeigniter-rest/health.svg)](https://phpackages.com/packages/inbo-codeigniter-rest)
```

###  Alternatives

[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.6k136.0M248](/packages/league-oauth2-server)[auth0/auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

40820.2M68](/packages/auth0-auth0-php)[yidas/codeigniter-rest

CodeIgniter 3 RESTful API Resource Base Controller

8215.7k2](/packages/yidas-codeigniter-rest)[ovh/ovh

Wrapper for OVHcloud APIs

3042.6M25](/packages/ovh-ovh)[auth0/symfony

Symfony SDK for Auth0 Authentication and Management APIs.

128738.1k](/packages/auth0-symfony)[mollie/oauth2-mollie-php

Mollie Provider for OAuth 2.0 Client

251.7M1](/packages/mollie-oauth2-mollie-php)

PHPackages © 2026

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