robert-grubb / coolapi
简单的PHP API框架
v1.9.2
2020-11-04 05:55 UTC
Requires
- php: >=5.4.0
- composer/composer: ^1.10
- robert-grubb/filerdb-php: ^1.2
README
注意:正在开发中
这是一个简单且快速的PHP API框架。
安装
请确保您已启用重写模块,并将以下内容放置在公共文件夹所在位置的下 .httaccess
文件中。注意:如果找不到CoolApi,则会抛出异常。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
注意:如果目录可写,API将尝试为您执行此操作。
composer require robert-grubb/coolapi
配置说明
以下所有值都是API设置的默认值。
$config = [
/**
* The baseUri is necessary if you are in a sub-directory on
* hosting. An example is: https:///foo/bar/api
*
* If you specify /foo/bar/api in baseUri, it will be removed
* from the URI when matching routes.
*/
'baseUri' => '/',
/**
* Log configuration:
*
* Logger requires a path that is writable, and the API will
* throw an exception if it is not. Below is the configuration
* for the logger.
*/
'logging' => [
'enabled' => true,
'path' => \CoolApi\Core\Utilities::root() . '/logs/',
'file' => 'api.log'
],
/**
* Configuration for cors
*/
'cors' => [
'enabled' => true,
'whitelist' => '*',
'blacklist' => false
],
/**
* Configuration for api keys
*
* With CoolApi, you can require api keys for access to your
* API. Look below for the configuration.
*
* CoolApi looks for the api key in 3 places:
* - Authorization: Bearer <api_key_here>
* - $_GET['key']
* - $_POST['key']
*
* Will accept a valid key from any of the above locations.
*/
'apiKeys' => [
'enabled' => false,
'keyField' => 'key', // What it looks for in $_GET or $_POST
'keys' => [] // Array of key strings
],
/**
* Configuration for Rate Limiting
*
* CoolApi comes with an out-of-the-box solution for rate limiting.
* In order for this to work properly, you must:
* 1. Provide a storage path (Look below for storage config) for FilerDB.
* 2. Enable it, and set a limit per window.
*/
'rateLimit' => [
'enabled' => false,
'limit' => 100, // Number of requests
'window' => (60 * 15) // In seconds (15 minutes)
],
/**
* Configuration for storage
* (rateLimit requires a storage path)
* Path: A writable directory somewhere on your filesystem.
*/
'storage' => [
'path' => false
]
];
使用示例
use CoolApi\Instance;
// Instantiate Cool Api
$api = new Instance($config);
// Setup home route
$api->router->get('/', function ($req, $res) {
// Return an output
$res->status(200)->output([
'foo' => 'bar'
]);
});
// Run the API
$api->run();
路由
为CoolApi添加路由非常简单,如下所示
$api->router->get('/test', function ($req, $res) { /** Code here **/ });
同样适用于POST、PUT或DELETE
$api->router->post('/test', function ($req, $res) { /** Code here **/ });
$api->router->put('/test', function ($req, $res) { /** Code here **/ });
$api->router->delete('/test', function ($req, $res) { /** Code here **/ });
在路由本身中使用参数
$api->router->post('/user/:id', function ($req, $res) {
// You can now access the id parameter via:
var_dump($req->param('id'));
});
如果参数不存在,将返回false。
要从请求中获取所有参数:$req->params
。
$api->router->use()
use()
方法允许您使用可以从前缀文件中导入的路由数组,以简单的方式组织代码。以下是定义路由并在另一个文件中导出的示例。
userRoutes.php
$data = function ($req, $res) {
$id = $req->param('id');
$res->output([
'id' => $id
]);
};
return [
':id/data' => [
'method' => 'get',
'handler' => $data
]
];
index.php
以下是导入userRoutes.php的方式
$userRoutes = require_once __DIR__ . '/userRoutes.php';
// Make use of routes from other files
$api->router->use('/user', $userRoutes);
// Or with middleware:
$api->router->use('/user', $middleware, $userRoutes);
现在您可以以GET路由的方式访问 /user/:id/data
。
使用 $req
获取POST或GET变量
$req->post('var_name'); // Returns $_POST['var_name'] || false
$req->get('var_name'); // Returns $_GET['var_name'] || false
$req->post() // Gets all $_POST variables
$req->get() // Gets all $_GET variables
从URL获取参数
// Returns false if it doesn't exist.
$req->param('id')
// Gets all parameters in object form
$req->params;
从请求中获取头信息
$req->headers(); // Returns all headers in array form
获取特定的头信息
$req->header('User-Agent');
使用 $res
返回正常响应
$res->output([
'foo' => 'bar'
]); // Treats it as a normal status of 200, and outputs as JSON.
设置状态码
$res->status(400)->output([]);
设置内容类型
$res->status(200)->contentType('plain')->output('plain text');
$res->status(200)->contentType('html')->output('<html></html>');
启用CORS层
[
/**
* Configuration for cors
*/
'cors' => [
'enabled' => true,
'whitelist' => '*',
'blacklist' => false
],
]
这允许所有站点访问您的API。
[
/**
* Configuration for cors
*/
'cors' => [
'enabled' => true,
'whitelist' => [
'https://www.google.com'
],
'blacklist' => false
],
]
这仅允许来自google.com的请求
[
/**
* Configuration for cors
*/
'cors' => [
'enabled' => true,
'whitelist' => '*',
'blacklist' => [
'https://www.google.com'
]
],
]
这允许除了google.com之外的任何地点的请求
请求中需要API密钥
您可以使用以下配置要求在请求期间需要API密钥来锁定您的API。
[
/**
* Configuration for api keys
*/
'apiKeys' => [
'enabled' => false,
'keyField' => 'key',
'keys' => [
'thisisanapikey'
]
],
]
keyField
仅在请求中不包含Authorization: Bearar头信息时检查。然后将在url中寻找?key=
,或在$_POST['key']
中寻找。
为特定密钥设置来源
[
/**
* Configuration for api keys
*/
'apiKeys' => [
'enabled' => false,
'keyField' => 'key',
'keys' => [
'thisisanapikey' => [
'origin' => 'www.facebook.com'
]
]
],
]
现在密钥 thisisanapikey
只能从来源 www.facebook.com
访问。
使用中间件
此API已设置,以便您可以在路由中使用自己的中间件。以下是一个示例
$middleware = function ($req, $res) {
if (!$req->header('User-Agent')) {
$res->status(400)->output([
'error' => true,
'message' => 'You must use a browser'
]);
}
return true; // Returning true, or returning nothing at all will pass.
}
/**
* Passing $middleware as the 2nd argument tells the api
* this needs to be ran before the handler method. If the middleware
* returns a bad status, or returns false, the handler will never
* be reached as the middleware fails.
*
* If the middleware returns true, then that means the handler can
* successfully be reached and ran.
*/
$api->router->get('/test', $middleware, function ($req, $res) {
// Do as you please here
});