参考文档: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

参看另一篇文章 http://www.cnblogs.com/ganiks/p/yii2-config.html

		'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']],
],
]

原创文章,转载请注明 http://www.cnblogs.com/ganiks/

.htaccess 不要遗漏

更新20140731:特别说明, 上面的 rules 配置有误, 用于 yii1.x 版本中的 rules (前三行)在这个地方时多余的,而且引起了一个很严重的 bug

参看另一篇随笔 http://www.cnblogs.com/ganiks/p/yii2-RESTful-API-405-Method-Not-Allowed.html

  1. 创建 News Model

http://localhost/gii/model

  1. 创建 News Controller

<?php

namespace app\controllers;

use yii\rest\ActiveController;

class NewsController extends ActiveController
{
public $modelClass = 'app\models\News';
}
  1. 测试

用Chrome工具 POSTMAN 测试

GET /news: list all news page by page;
HEAD /news: show the overview information of new listing;
POST /news: create a new new;
GET /news/123: return the details of the new 123;
HEAD /news/123: show the overview information of new 123;
PATCH /news/123 and PUT /news/123: update the new 123;
DELETE /news/123: delete the new 123;
OPTIONS /news: show the supported verbs regarding endpoint /news;
OPTIONS /news/123: show the supported verbs regarding endpoint /news/123.

遗留问题: 如何用 POSTMAN 工具测试 PUT 方法?

用 CURL 命令行测试

GET 方法

E:\>curl http://192.168.4.126/news/126
{
"array": {
"type": "yii\\web\\UnauthorizedHttpException",
"name": "Unauthorized",
"message": "You are requesting with an invalid access token.",
"code": 0,
"status": 401
}
}

授权访问

E:\>curl http://192.168.4.126/news/126?access-token=100-token
{
"array": {
"id": "126",
"image": "201_img.jpg",
"link": "http:\\/\\/www.surveymonkey.com\\/s\\/HZYZ3ZZ",
"show_date": "2012-05-15",
"state": 1,
"show_order": 18
}
}

PUT 方法

E:\>curl -X PUT -d image="test_method_put" http://192.168.4.126/news/126
{
"array": {
"type": "yii\\web\\UnauthorizedHttpException",
"name": "Unauthorized",
"message": "You are requesting with an invalid access token.",
"code": 0,
"status": 401
}
} E:\>curl -X PUT -d image="test_method_put" http://192.168.4.126/news/126?access-token=100-token
{
"array": {
"id": "126",
"image": "test_method_put",
"link": "http:\\/\\/www.surveymonkey.com\\/s\\/HZYZ3ZZ",
"show_date": "2012-05-15",
"state": 1,
"show_order": 18
}
} E:\>curl http://192.168.4.126/news/126?access-token=100-token
{
"array": {
"id": "126",
"image": "test_method_put",
"link": "http:\\/\\/www.surveymonkey.com\\/s\\/HZYZ3ZZ",
"show_date": "2012-05-15",
"state": 1,
"show_order": 18
}
}

DELETE 方法

E:\>curl -X DELETE http://192.168.4.126/news/126?access-token=100-token

E:\>curl http://192.168.4.126/news/126?access-token=100-token
{
"array": {
"type": "yii\\web\\NotFoundHttpException",
"name": "Not Found",
"message": "Object not found: 126",
"code": 0,
"status": 404
}
}

POST 方法

E:\>curl -X POST -d image="test_method_post" http://192.168.4.126/news?access-token=100-token
{
"array": {
"image": "test_method_post",
"id": "165"
}
} E:\>curl http://192.168.4.126/news/165?access-token=100-token
{
"array": {
"id": "165",
"image": "test_method_post",
"link": "",
"show_date": "0000-00-00",
"state": 1,
"show_order": 0
}
}

其他方法

E:\>curl -X OPTIONS http://192.168.4.126/news/165?access-token=100-token

E:\>curl -X OPTIONS http://192.168.4.126/news?access-token=100-token

E:\>curl -X HEAD http://192.168.4.126/news?access-token=100-token

E:\>curl -i http://192.168.4.126/news/165?access-token=100-token
HTTP/1.1 200 OK
Date: Thu, 31 Jul 2014 06:37:40 GMT
Server: Apache/2.2.9 (Win32) PHP/5.4.30 mod_fcgid/2.3.6
X-Powered-By: PHP/5.4.30
Content-Length: 99
Content-Type: application/json; charset=UTF-8 {"id":"165","image":"test_method_post","link":"","show_date":"0000-00-00","state":1,"show_order":0}
E:\>
  1. Restful Api 验证和授权

首先参看我的另一篇译文 http://www.cnblogs.com/ganiks/p/Yii2-RESTful-Authentication-and-Authorization.html

官方文档中介绍了3种发送 access-token 的方法, 方便测试的有 http basic Auth 以及 Query parameter 两种

这里简单介绍下配置的流程:

  • config/web.php 设置 enableSession
        'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'enableSession' => false,
]
  • controllers/news.php
use yii\filters\auth\HttpBasicAuth;
use yii\helpers\ArrayHelper;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
#这个地方使用`ComopositeAuth` 混合认证
'class' => CompositeAuth::className(),
#`authMethods` 中的每一个元素都应该是 一种 认证方式的类或者一个 配置数组
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
]
]
]);
}
  • models/User.php
    private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
'accessToken' => '101-token',
],
];
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
} return null;
}

两种方式测试一下:

  1. 访问 http://192.168.4.126/news/122 ,在弹出的登录对话框中输入用户名

    100-token 或者 101-token, 密码任意,登录
  2. 直接访问 http://192.168.4.126/news/122?access-token=101-token

yii2 RESTful API Develop的更多相关文章

  1. RESTful API Develop

    yii2 RESTful API Develop   参考文档:http://www.yiiframework.com/doc-2.0/guide-rest.html 以 DB 中的 news 表为例 ...

  2. Yii2 Restful Api 401

    采用Yii2 Restful Api方式为APP提供数据,默认你已经做好了所有的编码和配置工作.采用Postman测试接口: 出现这个画面的一个可能原因是:access_token的写法有误,如果你使 ...

  3. Yii2 restful api创建,认证授权以及速率控制

    Yii2 restful api创建,认证授权以及速率控制 下面是对restful从创建到速率控制的一个详细流程介绍,里面的步骤以及截图尽可能详细,熟悉restful的盆友可能觉得过于繁琐,新手不妨耐 ...

  4. yii2 RESTful API 405 Method Not Allowed

    关于 Yii2 中 RESTful API 的开发,可以参考另一篇随笔 http://www.cnblogs.com/ganiks/p/yii2-restful-api-dev.html 测试的过程中 ...

  5. Yii2 Restful api设计--App接口编程

    Yii2框架写一套RESTful风格的API,对照魏曦教你学 一,入门 一.目录结构 实现一个简单地RESTful API只需用到三个文件.目录如下: frontend ├─ config │ └ m ...

  6. yii2 restful api——app接口编程实例

    <?php namespace common\components; use common\models\Cart; use common\models\User; use Yii; use y ...

  7. Yii2 Restful API 原理分析

    Yii2 有个很重要的特性是对 Restful API的默认支持, 通过短短的几个配置就可以实现简单的对现有Model的RESTful API 参考另一篇文章: http://www.cnblogs. ...

  8. yii2 RESTful api的详细使用

    作者:白狼 出处:http://www.manks.top/yii2-restful-api.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则 ...

  9. yii2 restful api --app接口编程

    转 http://www.yiichina.com/tutorial/1143yii2中restful url访问配置, 登陆接口access-token验证类 [ 2.0 版本 ] 登陆接口acce ...

随机推荐

  1. Hadoop 伪分布式上安装 Hive

    下载地址:点此链接(P.S.下载带bin的安装包) 下载hive后放到虚拟机文件夹内,打开: -bin.tar.gz -C /home/software/ 修改并保存环境配置: gedit /etc/ ...

  2. 7个高级技巧帮助你释放大量Mac OS X硬盘空间

    7个高级技巧帮助你释放大量Mac OS X硬盘空间 https://blog.csdn.net/hu434587115/article/details/72874811/

  3. php.in

    [PHP] ;;;;;;;;;;; ; WARNING ; ;;;;;;;;;;; ; This is the default settings file for new PHP installati ...

  4. 【资料总结】html开发小实例

    目 录 第1章 1 HTML的基本标签 1 第2章 25 表格基础 25 第3章 53 表单和框架 53 第4章 77 CSS样式表 77 第5章 104 使用Dreamweaver制作网页 104 ...

  5. Mybatis错误:Result Maps collection already contains value for 。。。。

    解决方法 原因:xml文件中存在重名对象,保持名称不要一样即可正常启动.因为我再次使用逆向工程生成mapper接口和xml文件时,忘了删除原来的xml文件,新生成的与旧的同时出现旧重复了. 那么我们在 ...

  6. python基础教程_学习笔记12:充电时刻——模块

    充电时刻--模块 python的标准安装包含一组模块,称为标准库. 模块 >>> import math >>> math.sin(0) 0.0 模块是程序 不论什 ...

  7. MySQL数据库的查询缓冲机制

    MySQL数据库的查询缓冲机制 2011-08-10 11:07 佚名 火魔网 字号:T | T 使用查询缓冲机制,可以极大地提高MySQL数据库查询的效率,节省查询所用的时间.那么查询缓冲机制是怎样 ...

  8. Mybatis学习记录(六)--开发中的小问题

    近期開始做项目,期间遇到一些小问题,开此贴记录一下 1.关于order by 今天写一个sql查询语句,用了order by可是一直没效果,后来才发现用了#{}取值,mybatis使用这个的话对于St ...

  9. Ffmpeg 视频教程 向视频中添加文字

    Ffmpeg支持添加文字功能,具体如何将文字叠加到视频中的每一张图片,FFmpeg调用了文字库FreeSerif.ttf.当我们 用到ffmpeg 添加文字功能时 我们需要先下载改文字库,下载地址是h ...

  10. Jquery如何序列化form表单数据为JSON对象 C# ADO.NET中设置Like模糊查询的参数 从客户端出现小于等于公式符号引发检测到有潜在危险的Request.Form 值 jquery调用iframe里面的方法 Js根据Ip地址自动判断是哪个城市 【我们一起写框架】MVVM的WPF框架(三)—数据控件 设计模式之简单工厂模式(C#语言描述)

    jquery提供的serialize方法能够实现. $("#searchForm").serialize();但是,观察输出的信息,发现serialize()方法做的是将表单中的数 ...