Skip to content

yidas/codeigniter-rest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CodeIgniter RESTful API


CodeIgniter 3 RESTful API Controller

Latest Stable Version Latest Unstable Version License


OUTLINE


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

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

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

This library requires the following:

  • PHP 5.4.0+
  • CodeIgniter 3.0.0+

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

  1. Create a controller to extend yidas\rest\Controller,
class ResourceController extends yidas\rest\Controller {}
  1. Add and implement action methods referring by Build Methods.

Then you could access RESTful API:

https://yourname.com/resources/api
https://yourname.com/resources/api/123

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

https://yourname.com/resources/ajax
https://yourname.com/resources/ajax/123

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

Routes Setting

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

https://yourname.com/resources
https://yourname.com/resources/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

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 Method URI (Routes Setting) Action Description
GET /photos index List the collection's members.
POST /photos store Create a new entry in the collection.
GET /photos/{photo} show Retrieve an addressed member of the collection.
PUT/PATCH /photos/{photo} update Update the addressed member of the collection.
DELETE /photos/{photo} delete Delete the addressed member of the collection.
DELETE /photos delete Delete the entire collection.

Without Routes Setting, the URI is like /photos/ajax & /photos/ajax/{photo}.

Build Methods:

You could make a resource controller by referring the Template of Resource Controller.

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, $requestData=null) {}
protected function delete($resourceID=null) {}

$requestData (array) is the raw body from request

$resourceID (string) is the addressed identity of the resource from request

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/ajax/ 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.

Usage

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

The PSR-7 request component yidas\http\request is loaded with yidas\rest\Controller, which provides input handler and HTTP Authentication.

Usage

getAuthCredentialsWithBasic()

Get Credentials with HTTP Basic Authentication

public array getAuthCredentialsWithBasic()

Example:

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

getAuthCredentialsWithBearer()

Get Credentials with OAuth 2.0 Authorization Framework: Bearer Token Usage

public string getAuthCredentialsWithBearer()

Example:

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

HTTP RESPONSE

The PSR-7 response component yidas\http\response is loaded with yidas\rest\Controller, which provides output handler and formatter.

Usage

json()

JSON output shortcut

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

Example:

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

setFormat()

Set Response Format into CI_Output

public self setFormat(string $format)

Example:

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

setData()

Set Response Data into CI_Output

public self setData(mixed $data)

Example:

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

send()

Sends the response to the client.

public void send()

Example:

$this->response->send();

REFERENCE