{"id":20549821,"url":"https://github.com/robertgrubb/coolapi","last_synced_at":"2025-04-14T11:06:35.806Z","repository":{"id":56494774,"uuid":"271414174","full_name":"RobertGrubb/coolapi","owner":"RobertGrubb","description":"A simple PHP API framework to get your backend layer up and running fast","archived":false,"fork":false,"pushed_at":"2020-11-04T05:56:13.000Z","size":70,"stargazers_count":7,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-14T11:06:30.150Z","etag":null,"topics":["api","api-key","authorization","key","php","php-api","rate","rate-limit","rate-limiting","router"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RobertGrubb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-06-11T00:28:29.000Z","updated_at":"2023-07-29T08:38:07.000Z","dependencies_parsed_at":"2022-08-15T19:50:27.213Z","dependency_job_id":null,"html_url":"https://github.com/RobertGrubb/coolapi","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobertGrubb%2Fcoolapi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobertGrubb%2Fcoolapi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobertGrubb%2Fcoolapi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobertGrubb%2Fcoolapi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RobertGrubb","download_url":"https://codeload.github.com/RobertGrubb/coolapi/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248868768,"owners_count":21174757,"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":["api","api-key","authorization","key","php","php-api","rate","rate-limit","rate-limiting","router"],"created_at":"2024-11-16T02:21:07.526Z","updated_at":"2025-04-14T11:06:35.786Z","avatar_url":"https://github.com/RobertGrubb.png","language":"PHP","readme":"# Cool API\n\n**NOTE: DEVELOPMENT IN PROGRESS**\n\nA new PHP API framework that is simple and fast.\n\n## Installation\n\nMake sure you have rewrite mod enabled, and you place the following in `.httaccess` where your public folder is located. **NOTE:** CoolApi will throw an exception if it's not found.\n\n```\nRewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^ index.php [QSA,L]\n```\n\n**NOTE: The API will attempt to do this soon for you if the directory is writable**\n\n`composer require robert-grubb/coolapi`\n\n## Configuration Explained\n\nAll values below are the defaults set by the API.\n\n```\n$config = [\n\n  /**\n   * The baseUri is necessary if you are in a sub-directory on\n   * hosting. An example is: http://localhost/foo/bar/api\n   *\n   * If you specify /foo/bar/api in baseUri, it will be removed\n   * from the URI when matching routes.\n   */\n  'baseUri' =\u003e '/',\n\n  /**\n   * Log configuration:\n   *\n   * Logger requires a path that is writable, and the API will\n   * throw an exception if it is not. Below is the configuration\n   * for the logger.\n   */\n  'logging' =\u003e [\n    'enabled' =\u003e true,\n    'path'    =\u003e \\CoolApi\\Core\\Utilities::root() . '/logs/',\n    'file'    =\u003e 'api.log'\n  ],\n\n  /**\n   * Configuration for cors\n   */\n  'cors'    =\u003e [\n    'enabled'   =\u003e true,\n    'whitelist' =\u003e '*',\n    'blacklist' =\u003e false\n  ],\n\n  /**\n   * Configuration for api keys\n   *\n   * With CoolApi, you can require api keys for access to your\n   * API. Look below for the configuration.\n   *\n   * CoolApi looks for the api key in 3 places:\n   * - Authorization: Bearer \u003capi_key_here\u003e\n   * - $_GET['key']\n   * - $_POST['key']\n   *\n   * Will accept a valid key from any of the above locations.\n   */\n  'apiKeys'    =\u003e [\n    'enabled'  =\u003e false,\n    'keyField' =\u003e 'key', // What it looks for in $_GET or $_POST\n    'keys'     =\u003e [] // Array of key strings\n  ],\n\n  /**\n   * Configuration for Rate Limiting\n   *\n   * CoolApi comes with an out-of-the-box solution for rate limiting.\n   * In order for this to work properly, you must:\n   * 1. Provide a storage path (Look below for storage config) for FilerDB.\n   * 2. Enable it, and set a limit per window.\n   */\n  'rateLimit' =\u003e [\n    'enabled' =\u003e false,\n    'limit'   =\u003e 100, // Number of requests\n    'window'  =\u003e (60 * 15) // In seconds (15 minutes)\n  ],\n\n  /**\n   * Configuration for storage\n   * (rateLimit requires a storage path)\n   * Path: A writable directory somewhere on your filesystem.\n   */\n  'storage' =\u003e [\n    'path'  =\u003e false\n  ]\n\n];\n```\n\n## Example of Usage\n\n```\nuse CoolApi\\Instance;\n\n// Instantiate Cool Api\n$api = new Instance($config);\n\n// Setup home route\n$api-\u003erouter-\u003eget('/', function ($req, $res) {\n\n  // Return an output\n  $res-\u003estatus(200)-\u003eoutput([\n    'foo' =\u003e 'bar'\n  ]);\n});\n\n// Run the API\n$api-\u003erun();\n```\n\n## Routing\n\nTo add a route for CoolApi, it's as simple as the following:\n\n```\n$api-\u003erouter-\u003eget('/test', function ($req, $res) { /** Code here **/ });\n```\n\nAnd is the same for POST, PUT, or DELETE\n\n```\n$api-\u003erouter-\u003epost('/test', function ($req, $res) { /** Code here **/ });\n$api-\u003erouter-\u003eput('/test', function ($req, $res) { /** Code here **/ });\n$api-\u003erouter-\u003edelete('/test', function ($req, $res) { /** Code here **/ });\n```\n\nUsing parameters in the route itself:\n\n```\n$api-\u003erouter-\u003epost('/user/:id', function ($req, $res) {\n\n  // You can now access the id parameter via:\n  var_dump($req-\u003eparam('id'));\n\n});\n```\n\nIf the parameter does not exist, it will return false.\n\nTo get all parameters from the request: `$req-\u003eparams`.\n\n## `$api-\u003erouter-\u003euse()`\n\nThe `use()` method allows you to use an array of routes that can be imported from other files to organize your code in a simple way. Below is an example of how to define a route in another file, and export it.\n\n#### userRoutes.php\n\n```\n$data = function ($req, $res) {\n  $id = $req-\u003eparam('id');\n\n  $res-\u003eoutput([\n    'id' =\u003e $id\n  ]);\n};\n\nreturn [\n  ':id/data' =\u003e [\n    'method'  =\u003e 'get',\n    'handler' =\u003e $data\n  ]\n];\n```\n\n\n#### index.php\n\nBelow is how you would import userRoutes.php\n\n```\n$userRoutes = require_once __DIR__ . '/userRoutes.php';\n\n// Make use of routes from other files\n$api-\u003erouter-\u003euse('/user', $userRoutes);\n\n// Or with middleware:\n$api-\u003erouter-\u003euse('/user', $middleware, $userRoutes);\n```\n\nNow you can access `/user/:id/data` as a GET route.\n\n## Use of $req\n\nGetting POST, or GET variables:\n\n```\n$req-\u003epost('var_name'); // Returns $_POST['var_name'] || false\n$req-\u003eget('var_name'); // Returns $_GET['var_name'] || false\n$req-\u003epost() // Gets all $_POST variables\n$req-\u003eget() // Gets all $_GET variables\n```\n\nGetting parameters from the URL:\n\n```\n// Returns false if it doesn't exist.\n$req-\u003eparam('id')\n\n// Gets all parameters in object form\n$req-\u003eparams;\n```\n\nGetting headers from the request\n\n```\n$req-\u003eheaders(); // Returns all headers in array form\n```\n\nGetting a specific header:\n\n```\n$req-\u003eheader('User-Agent');\n```\n\n## Use of $res\n\nReturning a normal response:\n\n```\n$res-\u003eoutput([\n  'foo' =\u003e 'bar'\n]); // Treats it as a normal status of 200, and outputs as JSON.\n```\n\nSetting the status:\n\n```\n$res-\u003estatus(400)-\u003eoutput([]);\n```\n\nSetting the content type:\n\n```\n$res-\u003estatus(200)-\u003econtentType('plain')-\u003eoutput('plain text');\n$res-\u003estatus(200)-\u003econtentType('html')-\u003eoutput('\u003chtml\u003e\u003c/html\u003e');\n```\n\n## Enabling Cors Layer\n\n```\n[\n  /**\n   * Configuration for cors\n   */\n  'cors'    =\u003e [\n    'enabled'   =\u003e true,\n    'whitelist' =\u003e '*',\n    'blacklist' =\u003e false\n  ],\n]\n```\n\nAbove will allow all sites to access your api.\n\n```\n[\n  /**\n   * Configuration for cors\n   */\n  'cors'    =\u003e [\n    'enabled'   =\u003e true,\n    'whitelist' =\u003e [\n      'https://www.google.com'\n    ],\n    'blacklist' =\u003e false\n  ],\n]\n```\n\nAbove only allows requests from google.com\n\n```\n[\n  /**\n   * Configuration for cors\n   */\n  'cors'    =\u003e [\n    'enabled'   =\u003e true,\n    'whitelist' =\u003e '*',\n    'blacklist' =\u003e [\n      'https://www.google.com'\n    ]\n  ],\n]\n```\n\nAbove allows requests from anywhere except google.com\n\n## Requiring an API Key in the request\n\nYou can use the following configuration to require an API key during the request to lockdown your API.\n\n```\n[\n  /**\n   * Configuration for api keys\n   */\n  'apiKeys'    =\u003e [\n    'enabled'  =\u003e false,\n    'keyField' =\u003e 'key',\n    'keys'     =\u003e [\n      'thisisanapikey'\n    ]\n  ],\n]\n```\n\n`keyField` is looked at only if the request does not include a Authorization: Bearar \u003cToken\u003e in the request. It will then look for a `?key=` in the url, or `$_POST['key']`.\n\n### Setting an origin for a specific key:\n\n```\n[\n  /**\n   * Configuration for api keys\n   */\n  'apiKeys'    =\u003e [\n    'enabled'  =\u003e false,\n    'keyField' =\u003e 'key',\n    'keys'     =\u003e [\n      'thisisanapikey' =\u003e [\n        'origin' =\u003e 'www.facebook.com'\n      ]\n    ]\n  ],\n]\n```\n\nNow the key `thisisanapikey` is only accessible from the origin `www.facebook.com`\n## Using Middleware\n\nThis api is setup so you can use your own middleware in the routes. Below is an example:\n\n```\n$middleware = function ($req, $res) {\n  if (!$req-\u003eheader('User-Agent')) {\n    $res-\u003estatus(400)-\u003eoutput([\n      'error' =\u003e true,\n      'message' =\u003e 'You must use a browser'\n    ]);\n  }\n\n  return true; // Returning true, or returning nothing at all will pass.\n}\n\n/**\n * Passing $middleware as the 2nd argument tells the api\n * this needs to be ran before the handler method. If the middleware\n * returns a bad status, or returns false, the handler will never\n * be reached as the middleware fails.\n *\n * If the middleware returns true, then that means the handler can\n * successfully be reached and ran.\n */\n$api-\u003erouter-\u003eget('/test', $middleware, function ($req, $res) {\n  // Do as you please here\n});\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frobertgrubb%2Fcoolapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frobertgrubb%2Fcoolapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frobertgrubb%2Fcoolapi/lists"}