{"id":15046396,"url":"https://github.com/moudarir/codeigniter-rest-api","last_synced_at":"2025-07-22T18:33:46.156Z","repository":{"id":65711383,"uuid":"597944570","full_name":"moudarir/codeigniter-rest-api","owner":"moudarir","description":"Codeigniter 3 API Rest with Basic or Bearer Authentication methods.","archived":false,"fork":false,"pushed_at":"2024-04-24T22:32:28.000Z","size":235,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-10-30T06:24:48.469Z","etag":null,"topics":["api","authentication","authorization","bearer","codeigniter","codeigniter3","mysql","php","rest","server"],"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/moudarir.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,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-06T03:37:01.000Z","updated_at":"2024-07-11T11:26:18.000Z","dependencies_parsed_at":null,"dependency_job_id":"54f7a130-3bb1-4bb0-8ae1-0ac639604bc1","html_url":"https://github.com/moudarir/codeigniter-rest-api","commit_stats":{"total_commits":49,"total_committers":1,"mean_commits":49.0,"dds":0.0,"last_synced_commit":"7cfbc18eb3134695689fc8165bc61362a2b4a539"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/moudarir/codeigniter-rest-api","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moudarir%2Fcodeigniter-rest-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moudarir%2Fcodeigniter-rest-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moudarir%2Fcodeigniter-rest-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moudarir%2Fcodeigniter-rest-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/moudarir","download_url":"https://codeload.github.com/moudarir/codeigniter-rest-api/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/moudarir%2Fcodeigniter-rest-api/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266552545,"owners_count":23947178,"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","status":"online","status_checked_at":"2025-07-22T02:00:09.085Z","response_time":66,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["api","authentication","authorization","bearer","codeigniter","codeigniter3","mysql","php","rest","server"],"created_at":"2024-09-24T20:53:03.990Z","updated_at":"2025-07-22T18:33:46.132Z","avatar_url":"https://github.com/moudarir.png","language":"PHP","readme":"# Codeigniter 3 API Rest\n[![GitHub release (latest)](https://img.shields.io/github/v/release/moudarir/codeigniter-rest-api)](https://packagist.org/packages/moudarir/codeigniter-rest-api)\n[![GitHub license](https://img.shields.io/github/license/moudarir/codeigniter-rest-api)](https://github.com/moudarir/codeigniter-rest-api/blob/master/LICENSE)\n\nA RESTful server implementation for Codeigniter 3 based on [CodeIgniter RestServer](https://github.com/chriskacerguis/codeigniter-restserver \"CodeIgniter RestServer\")\n\n\u003e **Break changes** made in version `3.0`. Full code refactoring and new route system implemented inspired from [Luthier CI](https://github.com/ingeniasoftware/luthier-ci \"Luthier CI\").\n\n## Table of contents\n1. [Requirements](#requirements)\n2. [Installation](#installation)\n3. [Implementation](#implementation)\n4. [Usage](#usage)\n5. [Postman collection](#postman-collection)\n6. [Todo](#todo)\n\n## Requirements\n- PHP: `7.4` to `8.2` tested.\n- Codeigniter: `^3.1.13`.\n- Composer\n\n## Installation\n\u003e The current version `3.0.*` requires php 7.4 or higher ([php supported versions](http://php.net/supported-versions.php))\n\nThis library uses [Composer](https://getcomposer.org/) to be installed.\n\nRun this command line (recommended) in the same path as your `composer.json` file:\n\n```bash\ncomposer require moudarir/codeigniter-rest-api\n```\n\nOr, In your `composer.json` file, add the following code in `require` section: \n\n```php\n{\n  ...\n  \"require\": {\n    ...\n    \"moudarir/codeigniter-rest-api\": \"^3.0\"\n  },\n  ...\n}\n```\n\nAnd then run:\n\n```bash\ncomposer install\n```\n\n## Implementation\n\n### Language / Translation\nYou can find the file associated with your language in the `application/language/` folder. Based on the `$config['language']` setting in your `[your-project]/application/config/config.php` configuration file.\n\n### Supported languages\n- English\n- French\n- Arabic\n\n### Files \u0026 Configuration\nThe first thing to do is copying all required files in your CI project:\n\n- `application/config/rest-api-server.php` =\u003e `[your-project]/application/config/rest-api-server.php` \n- `application/controllers/DefaultController.php` =\u003e `[your-project]/application/controllers/DefaultController.php`\n- `application/language/*/rest-api-server_lang.php` =\u003e `[your-project]/application/language/*/rest-api-server_lang.php`\n- `application/routes/*` =\u003e `[your-project]/application/routes/*`\n\n\u003e **DO NOT** change the `[your-project]/application/config/rest-api-server.php` and `[your-project]/application/language/*/rest-api-server_lang.php` filenames.\n\nMake sure that the `enable_hooks` and `composer_autoload` keys in `[your-project]/application/config/config.php` file are set as following:\n\n```php\n$config['enable_hooks'] = true;\n$config['composer_autoload'] = true; // Or the path to 'autoload.php' file. Ex: APPPATH.'vendor/autoload.php'\n```\n\nNext, set the following code in `[your-project]/application/config/hooks.php` file:\n\n```php\n$hook = \\Moudarir\\CodeigniterApi\\Routes\\Hook::initialize();\n```\n\nand in `[your-project]/application/config/routes.php` file:\n```php\n$route = \\Moudarir\\CodeigniterApi\\Routes\\Router::getRoutes();\n```\n\n### Important\nExecute the `dumping/queries.sql` file to create the tables needed for the API to work properly.\n\nTables that will be created are `users`, `api_keys`, `api_key_limits` and `api_key_logs`.\n\nYou're now ready to begin using the library 👌.\n\n### About Routes\nThe implementation of old routes is deprecated. The routes are now simplified for best use. See [Usage](#usage).\n\n## Usage\nAdding some routes for the next example in `[your-project]/application/routes/api.php` file (if not exists).\n\n```php\n\\Moudarir\\CodeigniterApi\\Routes\\Router::group('users', ['namespace' =\u003e 'api'], function () {\n    \\Moudarir\\CodeigniterApi\\Routes\\Router::get('', 'apiUsers@index');\n    \\Moudarir\\CodeigniterApi\\Routes\\Router::post('', 'apiUsers@create');\n    \\Moudarir\\CodeigniterApi\\Routes\\Router::post('login', 'apiUsers@login');\n    \\Moudarir\\CodeigniterApi\\Routes\\Router::put('{id}', 'apiUsers@update');\n    \\Moudarir\\CodeigniterApi\\Routes\\Router::get('{id}', 'apiUsers@show');\n});\n\n// This will generate route array like this:\n/**\n$route = [\n  \"users\" =\u003e [\n    \"GET\" =\u003e \"api/apiUsers/index\",\n    \"POST\" =\u003e \"api/apiUsers/create\",\n  ],\n  \"users/login\" =\u003e [\n    \"POST\" =\u003e \"api/apiUsers/login\"\n  ],\n  \"users/([0-9]+)\" =\u003e [\n    \"PUT\" =\u003e \"api/apiUsers/update/$1\"\n    \"GET\" =\u003e \"api/apiUsers/show/$1\"\n  ],\n  \"default_controller\" =\u003e \"welcome\", // Can be changed in '[your-project]/application/config/rest-api-server.php' file.\n  \"translate_uri_dashes\" =\u003e false, // Can be changed in '[your-project]/application/config/rest-api-server.php' file.\n  \"404_override\" =\u003e \"pageNotFound/index\", // Can be changed in '[your-project]/application/config/rest-api-server.php' file.\n]\n**/\n```\n\nAnd now, we can create our `[your-project]/application/controllers/api/ApiUsers.php` controller:\n\n```php\n\u003c?php\ndefined('BASEPATH') || exit('No direct script access allowed');\n\nuse Firebase\\JWT\\JWT;\nuse Moudarir\\CodeigniterApi\\Exceptions\\DatabaseCreateException;\nuse Moudarir\\CodeigniterApi\\Http\\Server;\nuse Moudarir\\CodeigniterApi\\Models\\ApiKey;\nuse Moudarir\\CodeigniterApi\\Models\\User;\n\nclass ApiUsers extends Server\n{\n\n    public function index()\n    {\n        $entity = new User();\n        $page = $this-\u003eget('page');\n        $total = $entity-\u003ecount();\n        $response = [\n            'total' =\u003e $total,\n            'items' =\u003e $total === 0 ? [] : $entity-\u003eall(['page' =\u003e $page, 'limit' =\u003e $this-\u003eget('limit')]),\n        ];\n\n        if ($page !== null) {\n            $response['page'] = (int)$page === 0 ? 1 : (int)$page;\n        }\n\n        self::getResponse()-\u003eok($response);\n    }\n\n    public function show(int $id)\n    {\n        if ($id \u003c= 0) {\n            self::getResponse()-\u003ebadRequest();\n        }\n\n        $item = (new User())-\u003efind($id);\n\n        if ($item === null) {\n            self::getResponse()-\u003enotFound();\n        }\n\n        self::getResponse()-\u003eok(['item' =\u003e $item]);\n    }\n\n    public function create()\n    {\n        $post = $this-\u003epost();\n        $errors = [];\n\n        if (array_key_exists('email', $post)) {\n            $email = $this-\u003epost('email');\n\n            if (empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {\n                $errors['email'] = \"This field is not a valid email address.\";\n            }\n        } else {\n            $errors['email'] = \"This field is required.\";\n        }\n\n        if (!empty($errors)) {\n            self::getResponse()-\u003eerror($errors);\n        }\n\n        $entity = new User();\n\n        try {\n            $hashedPassword = password_hash($post['password'], PASSWORD_ARGON2I, [\n                'memory_cost' =\u003e 1 \u003c\u003c 12,\n                'time_cost' =\u003e 2,\n                'threads' =\u003e 2\n            ]);\n            $entity::getDatabase()-\u003etrans_start();\n            $user = $entity\n                -\u003esetFirstname($post['firstname'])\n                -\u003esetLastname($post['lastname'])\n                -\u003esetEmail($post['email'])\n                -\u003esetPassword($hashedPassword)\n                -\u003ecreate();\n\n            $apikey = (new ApiKey())\n                -\u003esetUserId($user-\u003egetId())\n                -\u003esetKey()\n                -\u003esetUsername()\n                -\u003esetPassword()\n                -\u003ecreate();\n\n            if ($entity::getDatabase()-\u003etrans_status() === false) {\n                $entity::getDatabase()-\u003etrans_rollback();\n            } else {\n                $entity::getDatabase()-\u003etrans_commit();\n            }\n\n            self::getResponse()-\u003eok([\n                'message' =\u003e \"User account created successfully.\",\n                'data' =\u003e [\n                    'user_id' =\u003e $user-\u003egetId(),\n                    'api_key' =\u003e $apikey-\u003egetKey(),\n                    'username' =\u003e $apikey-\u003egetUsername(),\n                    'password' =\u003e $apikey-\u003egetPassword(),\n                ]\n            ]);\n        } catch (DatabaseCreateException $e) {\n            $entity::getDatabase()-\u003etrans_rollback();\n            self::getResponse()-\u003eerror(\"Error occurred during account creation.\");\n        }\n    }\n\n    public function update($id)\n    {\n        self::getResponse()-\u003eok([\n            'data' =\u003e [\n                'info' =\u003e $this-\u003egetAuthData(),\n                'args' =\u003e $this-\u003eput(),\n                'id' =\u003e $id,\n            ]\n        ]);\n    }\n\n    public function login()\n    {\n        $apiConfig = $this-\u003egetApiConfig();\n        $secret = getenv(\"JWT_SECRET\");\n        $secret !== false || $secret = $apiConfig['jwt_secret'];\n        $user = (new User())-\u003efind($this-\u003egetApiKey()['user_id']);\n        $payload = [\n            'iss' =\u003e 'http://example.org',\n            'aud' =\u003e 'http://example.com',\n            'iat' =\u003e 1356999524,\n            'nbf' =\u003e 1357000000,\n            'user' =\u003e [\n                'user_id' =\u003e $user['id'],\n                'firstname' =\u003e $user['firstname'],\n                'lastname' =\u003e $user['lastname'],\n                'email' =\u003e $user['email'],\n            ]\n        ];\n        self::getResponse()-\u003eok([\n            'data' =\u003e [\n                'jwt_key' =\u003e JWT::encode($payload, $secret, $apiConfig['jwt_algorithm']),\n            ]\n        ]);\n    }\n}\n```\n\n### Authentication methods\nThe Rest Server can be used with `Basic` or `Bearer` authorization type. However, it can be used without any authorization type (`not secure`).\n\nThe request limit currently only works in the `Basic` authorization type.\n\n## Postman collection\n\n### Import the collection\nDownloaded our [Postman collection](https://github.com/moudarir/codeigniter-rest-api/blob/master/Codeigniter%20API%20REST.postman_collection.json \"Codeigniter REST API Postman Collection\"), and import it into Postman.\n\n### Import the environment\nWe have also provided a [Postman Environment](https://github.com/moudarir/codeigniter-rest-api/blob/master/Codeigniter%20API%20REST.postman_environment.json \"Codeigniter REST API Postman Environment\") that you need to import as well.\n\n\u003e To understand what Postman environments are, please check [this link](https://learning.postman.com/docs/sending-requests/managing-environments/ \"Managing environments in Postman\").\n\n### Edit the environment variables\nUpdate the `endpoint` variable to point to your Rest server. Ex: (https//myapi.com/) with trailing slash.\n\n✨ That's it!\n\nYou can now use the Postman collection to test available requests.\n\n\u003e In the Postman collection, the order of execution of the requests must be respected.\n\n## Todo\n- Write routing HOW TO USE documentation.\n- Improve documentation.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoudarir%2Fcodeigniter-rest-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmoudarir%2Fcodeigniter-rest-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmoudarir%2Fcodeigniter-rest-api/lists"}