参考文档:http://www.yiiframework.com/doc-2.0/guide-rest.html
以 DB 中的 news 表为例创建该资源的 RESTful API,最终的测试通过工具 POSTMAN 测试如下图;
通过 yii2 ,非常方便的创建 RESTful API
步骤:
- 准备工作,配置友好的 URLManager
- 创建News Model (via gii)
- 创建News Controller
- 测试用 POSTMAN 工具或者 CURL
- Restful Api 验证和授权
1. 配置 friendly Url
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
['class' => 'yii\rest\UrlRule', 'controller' => ['user', 'news']],
],
]
.htaccess 不要遗漏
更新20140731:特别说明, 上面的
rules
配置有误, 用于yii1.x
版本中的rules
(前三行)在这个地方时多余的,而且引起了一个很严重的 bug【
测试的过程中遇到一个这样的问题, 报错 405 yii2 RESTful API 405 Method Not Allowed
比如请求 PUT 方法 的 http://192.168.4.126/news/162?access-token=100-token
{ "type": "yii\\web\\MethodNotAllowedHttpException", "name": "Method Not Allowed", "message": "Method Not Allowed. This url can only handle the following request methods: GET, HEAD.", "code": 0, "status": 405 }
这里由于不是在 yii2 的前台框架体系中,因此没有看到堆栈的调试信息,但是要调试也要找到这个报错 message 的所在:
yii2\filters\VerbFilter.php
public function beforeAction($event) { $action = $event->action->id; if (isset($this->actions[$action])) { $verbs = $this->actions[$action]; } elseif (isset($this->actions['*'])) { $verbs = $this->actions['*']; } else { return $event->isValid; } $verb = Yii::$app->getRequest()->getMethod(); $