All Projects → yidas → codeigniter-rest

yidas / codeigniter-rest

Licence: MIT license
CodeIgniter 3 RESTful API Resource Base Controller

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to codeigniter-rest

Codeigniter Jwt Sample
CodeIgniter JWT Sample
Stars: ✭ 144 (+102.82%)
Mutual labels:  codeigniter, restful-api
go-pangu
rest api web server based on go(High availability, high security, high performance)
Stars: ✭ 45 (-36.62%)
Mutual labels:  restful-api, rest-server
grapevine
Fast, unopinionated, embeddable, minimalist web framework for .NET
Stars: ✭ 72 (+1.41%)
Mutual labels:  restful-api, rest-server
socialigniter
This is core install of social igniter application. Please follow the Readme below
Stars: ✭ 78 (+9.86%)
Mutual labels:  codeigniter
tastjava
The RESTful Web API framework for Java
Stars: ✭ 27 (-61.97%)
Mutual labels:  restful-api
pong
🏓 Pong for RESTful APIs (microservices pattern) using Serverless Framework ⚡
Stars: ✭ 27 (-61.97%)
Mutual labels:  restful-api
lowdb-api
⚡️ lowdb-api - Express middleware that serve a virtual RESTful API.
Stars: ✭ 27 (-61.97%)
Mutual labels:  restful-api
Rhythm-CB-Scripts
Collection of scripts for use with Carbon Black Cb Response API
Stars: ✭ 14 (-80.28%)
Mutual labels:  restful-api
node-server
(@nestjs refactoring)⚡️My personal website's api server, a RESTful application that powered by @eggjs
Stars: ✭ 17 (-76.06%)
Mutual labels:  restful-api
Slice-Library
Slice-Library is a CodeIgniter library that simulates Laravel's Blade templating system!
Stars: ✭ 60 (-15.49%)
Mutual labels:  codeigniter
OpenTor-X
Open Source Torrent Index Website
Stars: ✭ 19 (-73.24%)
Mutual labels:  codeigniter
modx2-api
MODX Revolution RESTful API
Stars: ✭ 16 (-77.46%)
Mutual labels:  restful-api
mssql-restapi
A simple REST API for SQL Server, Azure SQL DB and Azure SQL DW using SMO on .NET Core 2.0
Stars: ✭ 33 (-53.52%)
Mutual labels:  restful-api
CodeIgniter-3.0.0-ORM-Twig
First CodeIgniter 3 using orm and template engine twig
Stars: ✭ 19 (-73.24%)
Mutual labels:  codeigniter
rimbun
Codeigniter Starter
Stars: ✭ 25 (-64.79%)
Mutual labels:  codeigniter
dhiwise-nodejs
DhiWise Node.js API generator allows you to instantly generate secure REST APIs. Just supply your database schema to DhiWise, and a fully documented CRUD APIs will be ready for consumption in a few simple clicks. The generated code is clean, scalable, and customizable.
Stars: ✭ 224 (+215.49%)
Mutual labels:  restful-api
sca-best-practice
Provide microservice API for HanLP
Stars: ✭ 13 (-81.69%)
Mutual labels:  restful-api
CIgniter-Datatables
CodeIgniter library for Datatables server-side processing / AJAX, easy to use :3
Stars: ✭ 39 (-45.07%)
Mutual labels:  codeigniter
cannercms
⚡️[NOT MAINTAINED] Content Management Framework creates custom CMS fast and easy. Support data sources such as Firebase/Firestore, GraphQL and Restful APIs.
Stars: ✭ 2,452 (+3353.52%)
Mutual labels:  restful-api
pulsarctl
a CLI for Apache Pulsar written in Go
Stars: ✭ 106 (+49.3%)
Mutual labels:  restful-api

CodeIgniter RESTful API


CodeIgniter 3 RESTful API Resource Base Controller

Latest Stable Version License

This RESTful API extension is collected into yidas/codeigniter-pack which is a complete solution for Codeigniter framework.

Features

  • PSR-7 standardization

  • RESTful API implementation

  • Laravel Resource Controllers pattern like


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 Resource extends yidas\rest\Controller {}
  1. Add and implement action methods referring by 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

If you want to have a standard RESTful URI pattern that controller defines as a URI resource, 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/(:any)'] = '[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.
PUT /photos update Update the entire 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/api & /photos/api/{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=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 data format of common content types. (Alternatively, use this->request->getRawBody() to get raw data)

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

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

_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

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 preloaded into yidas\rest\Controller, which provides input handler and HTTP Authentication. You could call it by $this->request in controller class.

Usage

getRawBody()

Returns the raw HTTP request body

public string getRawBody()

Example:

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

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 preloaded into yidas\rest\Controller, which provides output handler and formatter. You could call it by $this->response in controller class.

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();

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].