irooit / yii-fast-api
用于在yii2框架上快速开发API的组件
0.2.0
2023-01-03 02:32 UTC
Requires
- yiisoft/yii2: ^2.0.9
This package is not auto-updated.
Last update: 2024-09-25 09:15:52 UTC
README
yii2-fast-api 是一个 Yii2 框架的扩展,用于配置完善的 Yii2,以实现 API 的快速开发。此扩展默认的场景是 APP 的后端接口开发,因此偏向于实用主义,并未完全采用 restfull 的标准,方便前端开发处理接口数据以及各种异常。
安装
使用 Composer 安装
- 在项目中的
composer.json
文件中添加依赖:
"require": {
"irooit/yii-fast-api": "^0.1.0"
}
执行
$ php composer.phar update
或$ composer update
进行安装。执行
$ composer require irooit/yii-fast-api
进行安装。在配置文件中( Yii2 高级版为 main.php,Yii2 基础版为 web.php )注入 fast-api 的配置:
// $config 为你原本的配置
$config = yii\helpers\ArrayHelper::merge(
$config,
\irooit\yii\rest\Controller::getConfig()
);
return $config;
用法
- 建立控制器
class YourController extends irooit\yii\rest\Controller
{
/**
* 示例接口
* @param int $id 请求参数
* @return string version api版本
* @return int yourId 你的请求参数
*/
public function actionIndex($id)
{
return ['version'=>'1.0.0','yourId'=>$id];
}
}
- 发送请求看看
正常请求
POST /your/index HTTP/1.1
Host: yoursite.com
Content-Type: application/json
{"id":"10"}
返回
{
"code": 200,
"data": {
"version": "1.0.0",
"yourId": "10"
},
"message": "OK"
}
缺少参数的请求
POST /your/index HTTP/1.1
Host: yoursite.com
Content-Type: application/json
返回错误
{
"code": 400,
"data": {},
"message": "缺少参数:id"
}
- 查看自动生成的 Api 文档
http ://yoursite.com/route/api/index
结语
感谢 @暗夜在火星 的 PhalApi 项目,为此 Yii2 扩展提供设计的思路。
待办事项
- 更完善的文档指南
- Signature 过滤器插件
- 限流插件的使用
- RequestID 以及日志存储追踪的参考