yii2-fast-api是一个Yii2框架的扩展,用于配置完善Yii2,以实现api的快速开发。php
此扩展默认的场景是APP的后端接口开发,所以偏向于实用主义,并未彻底采用restfull的标准,方便前端开发处理接口数据以及各类异常。前端
composer.json
文件中添加依赖:"require": { "deepziyu/yii-fast-api": "*" }
执行 $ php composer.phar update
或 $ composer update
进行安装。web
在配置文件中( Yii2 高级版为 main.php,Yii2 基础版为 web.php )注入 fast-api 的配置:json
// $config 为你本来的配置 $config = yiihelpersArrayHelper::merge( $config, deepziyuyiirestController::getConfig() ); return $config;
class YourController extends deepziyuyiirestController { /** * 示例接口 * @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"}
返回api
{ "code": 200, "data": { "version": "1.0.0", "yourId": "10" }, "message": "OK" }
缺乏参数的请求restful
POST /your/index HTTP/1.1 Host: yoursite.com Content-Type: application/json
返回错误yii2
{ "code": 400, "data": {}, "message": "缺乏参数:id" }
http ://yoursite.com/route/api/indexapp
感谢@暗夜在火星 的PhalApi项目,为此Yii2扩展提供设计的思路。composer
本文转自码云推荐 | 基于 yii2 的快速配置 api 服务 yii2-fast-api,仅供学习交流使用!