{"id":14987262,"url":"https://github.com/yidas/codeigniter-rest","last_synced_at":"2025-04-10T04:59:48.147Z","repository":{"id":37933490,"uuid":"115614387","full_name":"yidas/codeigniter-rest","owner":"yidas","description":"CodeIgniter 3 RESTful API Resource Base Controller","archived":false,"fork":false,"pushed_at":"2023-02-22T03:08:55.000Z","size":63,"stargazers_count":81,"open_issues_count":1,"forks_count":31,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-04-03T01:11:18.971Z","etag":null,"topics":["codeigniter","codeigniter-rest","json","rest","rest-server","restful-api"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yidas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-12-28T10:55:13.000Z","updated_at":"2024-10-22T15:35:01.000Z","dependencies_parsed_at":"2024-01-15T01:28:00.198Z","dependency_job_id":null,"html_url":"https://github.com/yidas/codeigniter-rest","commit_stats":{"total_commits":44,"total_committers":1,"mean_commits":44.0,"dds":0.0,"last_synced_commit":"58620a738e2c5d316b42d4ead51f350ab6e8b311"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yidas%2Fcodeigniter-rest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yidas%2Fcodeigniter-rest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yidas%2Fcodeigniter-rest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yidas%2Fcodeigniter-rest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yidas","download_url":"https://codeload.github.com/yidas/codeigniter-rest/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248161267,"owners_count":21057554,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["codeigniter","codeigniter-rest","json","rest","rest-server","restful-api"],"created_at":"2024-09-24T14:14:20.836Z","updated_at":"2025-04-10T04:59:48.124Z","avatar_url":"https://github.com/yidas.png","language":"PHP","readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://codeigniter.com/\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://camo.githubusercontent.com/b1df5003f5bc21277aeb87c5d3558242b74eb54a61a253cc061a38c7a43bcac7/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f7a682f372f37632f436f646549676e697465722e706e67\" height=\"\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eCodeIgniter RESTful API\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\nCodeIgniter 3 RESTful API Resource Base Controller\n\n[![Latest Stable Version](https://poser.pugx.org/yidas/codeigniter-rest/v/stable?format=flat-square)](https://packagist.org/packages/yidas/codeigniter-rest)\n[![License](https://poser.pugx.org/yidas/codeigniter-rest/license?format=flat-square)](https://packagist.org/packages/yidas/codeigniter-rest)\n\nThis RESTful API extension is collected into [yidas/codeigniter-pack](https://github.com/yidas/codeigniter-pack) which is a complete solution for Codeigniter framework.\n\nFeatures\n--------\n\n- ***PSR-7** standardization*\n\n- ***RESTful API** implementation*\n\n- ***Laravel Resource Controllers** pattern like* \n\n---\n\nOUTLINE\n-------\n\n- [Demonstration](#demonstration)\n    - [RESTful Create Callback](#restful-create-callback)\n    - [Packed Standard Format](#packed-standard-format)\n- [Requirements](#requirements)\n- [Installation](#installation)\n- [Configuration](#configuration)\n    - [Routes Setting](#routes-setting)\n- [Resource Controllers](#resource-controllers)\n    - [Build Methods](#build-methods)\n    - [Custom Routes \u0026 Methods](#custom-routes--methods)\n    - [Behaviors](#behaviors)\n    - [Usage](#usage)\n- [HTTP Request](#http-request)\n    - [Usage](#usage-1)\n- [HTTP Response](#http-response)\n    - [Usage](#usage-2)\n- [Reference](#reference)\n\n---\n\nDEMONSTRATION\n-------------\n\n```php\nclass ApiController extends yidas\\rest\\Controller\n{\n    public function index()\n    {\n        return $this-\u003eresponse-\u003ejson(['bar'=\u003e'foo']);\n    }\n}\n```\n\nOutput with status `200 OK`:\n\n```json\n{\"bar\":\"foo\"}\n```\n\n### RESTful Create Callback\n\n```php\npublic function store($requestData=null) {\n\n    $this-\u003edb-\u003einsert('mytable', $requestData);\n    $id = $this-\u003edb-\u003einsert_id();\n    \n    return $this-\u003eresponse-\u003ejson(['id'=\u003e$id], 201);\n}\n```\n\nOutput with status `201 Created`:\n\n```json\n{\"id\":1}\n```\n\n### Packed Standard Format\n\n```php\ntry {\n    throw new Exception(\"API forbidden\", 403);\n} catch (\\Exception $e) {\n    // Pack data into a standard format\n    $data = $this-\u003epack(['bar'=\u003e'foo'], $e-\u003egetCode(), $e-\u003egetMessage());\n    return $this-\u003eresponse-\u003ejson($data, $e-\u003egetCode());\n}\n\n```\n\nOutput with status `403 Forbidden`:\n\n```json\n{\"code\":403,\"message\":\"API forbidden\",\"data\":{\"bar\":\"foo\"}}\n```\n\n---\n\nREQUIREMENTS\n------------\nThis library requires the following:\n\n- PHP 5.4.0+\n- CodeIgniter 3.0.0+\n\n---\n\nINSTALLATION\n------------\n\nRun Composer in your Codeigniter project under the folder `\\application`:\n\n    composer require yidas/codeigniter-rest\n    \nCheck Codeigniter `application/config/config.php`:\n\n```php\n$config['composer_autoload'] = TRUE;\n```\n    \n\u003e You could customize the vendor path into `$config['composer_autoload']`\n\n---\n\nCONFIGURATION\n-------------\n\n1. Create a controller to extend `yidas\\rest\\Controller`, \n\n```php\nclass Resource extends yidas\\rest\\Controller {}\n```\n\n2. Add and implement action methods referring by [Build Methods](#build-methods).\n\nThen you could access RESTful API:\n\n```\nhttps://yourname.com/resource/api\nhttps://yourname.com/resource/api/123\n```\n\nYou could also use `/ajax` instead of `/api` if you like:\n\n```\nhttps://yourname.com/resource/ajax\nhttps://yourname.com/resource/ajax/123\n```\n\n\u003e `resource` is Controller name, if you don't want to have `/api` or `/ajax` in URI you could set Routes Setting as below.\n\n### Routes Setting\n\nIf you want to have a standard RESTful URI pattern that controller defines as a URI resource, for example:\n\n```\nhttps://yourname.com/resource\nhttps://yourname.com/resource/123\n```\n\nYou could add a pair of routes for this controller into `\\application\\config\\routes.php` to enable RESTful API url:\n\n```php\n$route['resource_name'] = '[Controller]/route';\n$route['resource_name/(:any)'] = '[Controller]/route/$1';\n```\n\n---\n\nRESOURCE CONTROLLERS\n--------------------\n \nThe 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:\n\n|HTTP Method|URI (Routes Setting) |Action   |Description                                    |\n|:----------|:--------------------|:--------|:----------------------------------------------|\n|GET        |/photos              |index    |List the collection's members.                 |\n|POST       |/photos              |store    |Create a new entry in the collection.          |\n|GET        |/photos/{photo}      |show     |Retrieve an addressed member of the collection.|\n|PUT/PATCH  |/photos/{photo}      |update   |Update the addressed member of the collection. |\n|PUT        |/photos              |update   |Update the entire collection.                  |\n|DELETE     |/photos/{photo}      |delete   |Delete the addressed member of the collection. |\n|DELETE     |/photos              |delete   |Delete the entire collection.                  |\n\n\u003e Without Routes Setting, the URI is like `/photos/api` \u0026 `/photos/api/{photo}`.\n\n\n### Build Methods:\n\nYou could make a resource controller by referring the [Template of Resource Controller](https://github.com/yidas/codeigniter-rest/blob/dev/examples/RestController.php).\n\nThe 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:\n\n```php\npublic function index() {}\nprotected function store($requestData=null) {}\nprotected function show($resourceID) {}\nprotected function update($resourceID=null, $requestData=null) {}\nprotected function delete($resourceID=null, $requestData=null) {}\n```\n\n\u003e `$resourceID` (string) is the addressed identity of the resource from request\n\u003e\n\u003e `$requestData` (array) is the array input data parsed from request raw body, which supports data format of common content types. (Alternatively, use [`this-\u003erequest-\u003egetRawBody()`](#getrawbody) to get raw data)\n\n### Custom Routes \u0026 Methods\n\nThe default routes for mapping the same action methods of Resource Controller are below:\n\n```php\nprotected $routes = [\n    'index' =\u003e 'index',\n    'store' =\u003e 'store',\n    'show' =\u003e 'show',\n    'update' =\u003e 'update',\n    'delete' =\u003e 'delete',\n];\n```\n\nYou could override it to define your own routes while creating a resource controller:\n\n```php\nclass ApiController extends yidas\\rest\\Controller {\n\n    protected $routes = [\n        'index' =\u003e 'find',\n        'store' =\u003e 'save',\n        'show' =\u003e 'display',\n        'update' =\u003e 'edit',\n        'delete' =\u003e 'destory',\n    ];\n}\n```\n\nAfter 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.\n\n\u003e The keys refer to the actions of Resource Controller table, you must define all methods you need. \n\n### Behaviors\n\nResource Controller supports behaviors setting for each action, you could implement such as authentication for different permissions.\n\n#### _setBehavior()\n\nSet behavior to a action before route\n\n```php\nprotected boolean _setBehavior(string $action, callable $function)\n```\n\n*Example:*\n```php\nclass BaseRestController extends \\yidas\\rest\\Controller\n{\n    function __construct() \n    {\n        parent::__construct();\n    \n        // Load your Auth library for verification\n        $this-\u003eload-\u003elibrary('Auth');\n        $this-\u003eauth-\u003everify('read');\n        \n        // Set each action for own permission verification\n        $this-\u003e_setBehavior('store', function() {\n            $this-\u003eauth-\u003everify('create');\n        });\n        $this-\u003e_setBehavior('update', function() {\n            $this-\u003eauth-\u003everify('update');\n        });\n        $this-\u003e_setBehavior('delete', function() {\n            $this-\u003eauth-\u003everify('delete');\n        });\n    }\n    // ...\n```\n\n### Usage\n\n#### pack()\n\nPack array data into body format\n\nYou could override this method for your application standard.\n\n```php\nprotected array pack(array|mixed $data, integer $statusCode=200, string $message=null)\n````\n\n*Example:*\n```php\n$data = $this-\u003epack(['bar'=\u003e'foo'], 403, 'Forbidden');\nreturn $this-\u003eresponse-\u003ejson($data, 403);\n```\n\nJSON Result:\n\n```\n{\n    \"code\": 403,\n    \"message\": \"Forbidden\",\n    \"data\": {\n        \"bar\": \"foo\"\n    }\n}\n```\n\n---\n\nHTTP REQUEST\n------------\n\nThe 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-\u003erequest` in controller class.\n\n### Usage\n\n#### getRawBody()\n\nReturns the raw HTTP request body\n\n```php\npublic string getRawBody()\n```\n\n*Example:*\n```php\n// Request with `application/json` raw\n$data = json_decode($this-\u003erequest-\u003egetRawBody);\n```\n\n#### getAuthCredentialsWithBasic()\n\nGet Credentials with HTTP Basic Authentication \n\n```php\npublic array getAuthCredentialsWithBasic()\n```\n\n*Example:*\n```php\nlist($username, $password) = $this-\u003erequest-\u003egetAuthCredentialsWithBasic();\n```\n\n#### getAuthCredentialsWithBearer()\n\nGet Credentials with OAuth 2.0 Authorization Framework: Bearer Token Usage\n\n```php\npublic string getAuthCredentialsWithBearer()\n```\n\n*Example:*\n```php\n$b64token = $this-\u003erequest-\u003egetAuthCredentialsWithBearer();\n```\n\n---\n\nHTTP RESPONSE\n-------------\n\nThe 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-\u003eresponse` in controller class.\n\n### Usage\n\n#### json()\n\nJSON output shortcut\n\n```php\npublic void json(array|mixed $data, integer $statusCode=null)\n```\n\n*Example:*\n```php\n$this-\u003eresponse-\u003ejson(['bar'=\u003e'foo'], 201);\n```\n\n#### setFormat()\n\nSet Response Format into CI_Output\n\n```php\npublic self setFormat(string $format)\n```\n\n*Example:*\n```php\n$this-\u003eresponse-\u003esetFormat(\\yidas\\http\\Response::FORMAT_JSON);\n```\n\n#### setData()\n\nSet Response Data into CI_Output\n\n```php\npublic self setData(mixed $data)\n```\n\n*Example:*\n```php\n$this-\u003eresponse-\u003esetData(['foo'=\u003e'bar']);\n```\n\n#### send()\n\nSends the response to the client.\n\n```php\npublic void send()\n```\n\n*Example:*\n```php\n$this-\u003eresponse-\u003esend();\n```\n\n#### withAddedHeader()\n\nReturn an instance with the specified header appended with the given value.\n\n```php\npublic self withAddedHeader(string $name, string $value)\n```\n\n*Example:*\n```php\nreturn $this-\u003eresponse\n    -\u003ewithAddedHeader('Access-Control-Allow-Origin', '*')\n    -\u003ewithAddedHeader('X-Frame-Options', 'deny')\n    -\u003ejson(['bar'=\u003e'foo']);\n```\n\n---\n\nREFERENCE\n---------\n\n- [HTTP authentication by MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication)\n\n- [RFC7617 - The 'Basic' HTTP Authentication Scheme](https://tools.ietf.org/html/rfc7617)\n\n- [RFC6750 - The OAuth 2.0 Authorization Framework: Bearer Token Usage](https://tools.ietf.org/html/rfc6750)\n\n- [REST Relationship between URL and HTTP methods](https://en.wikipedia.org/wiki/Representational_state_transfer#Relationship_between_URI_and_HTTP_methods)\n\n- [PSR-7: HTTP message interfaces](https://www.php-fig.org/psr/psr-7/)\n","funding_links":[],"categories":["Web Services"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyidas%2Fcodeigniter-rest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyidas%2Fcodeigniter-rest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyidas%2Fcodeigniter-rest/lists"}