yii2 RESTful API Develop

 

参考文档: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
  • 测试
  • 高级

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 不要遗漏

2. 创建 News Model

http://localhost/gii/model

3. 创建 News Controller

<?php

namespace app\controllers;

use yii\rest\ActiveController;

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

4. 用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.

5. 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, rest

RESTful API Develop的更多相关文章

  1. yii2 RESTful API Develop

    参考文档:http://www.yiiframework.com/doc-2.0/guide-rest.html 以 DB 中的 news 表为例创建该资源的 RESTful API,最终的测试通过工 ...

  2. Laravel API Tutorial: How to Build and Test a RESTful API

    With the rise of mobile development and JavaScript frameworks, using a RESTful API is the best optio ...

  3. Flask (五) RESTful API

    RESTful API 什么是REST 一种软件架构风格.设计风格.而不是标准,只是提供了一组设计原则和约束条件.它主要用户客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易 ...

  4. 可以执行全文搜索的原因 Elasticsearch full-text search Kibana RESTful API with JSON over HTTP elasticsearch_action es 模糊查询

    https://www.elastic.co/guide/en/elasticsearch/guide/current/getting-started.html Elasticsearch is a ...

  5. (转载) RESTful API 设计指南

    作者: 阮一峰 日期: 2014年5月22日 网络应用程序,分为前端和后端两个部分.当前的发展趋势,就是前端设备层出不穷(手机.平板.桌面电脑.其他专用设备......). 因此,必须有一种统一的机制 ...

  6. Node.js实现RESTful api,express or koa?

    文章导读: 一.what's RESTful API 二.Express RESTful API 三.KOA RESTful API 四.express还是koa? 五.参考资料 一.what's R ...

  7. Restful Api 最佳实践

    Web APIs has become an very important topic in the last year. We at M-Way Solutions are working ever ...

  8. 基于轻量型Web服务器Raspkate的RESTful API的实现

    在上一篇文章中,我们已经了解了Raspkate这一轻量型Web服务器,今天,我们再一起了解下如何基于Raspkate实现简单的RESTful API. 模块 首先让我们了解一下"模块&quo ...

  9. RESTful Api 身份认证安全性设计

    REST是一种软件架构风格.RESTful Api 是基于 HTTP 协议的 Api,是无状态传输.它的核心是将所有的 Api 都理解为一个网络资源.将所有的客户端和服务器的状态转移(动作)封装到 H ...

随机推荐

  1. 开源TinyXML 最简单的新手教程

    TinyXML它是基于一个非常受欢迎的现在DOM型号XML解析器,简单易用且小巧玲珑,很适合存储简单数据.配置文件. 该项目属于开源项目,在sourceforge上边的链接是:http://sourc ...

  2. 83. 从视图索引说Notes数据库(上)

    索引是数据库系统重要的feature,不管是传统的关系型数据库还是时兴的NoSQL数据库,它攸关查询性能,因而在设计数据库时须要细加考量.然而,Lotus Notes隐藏技术底层.以用户界面为导向.追 ...

  3. Caused by: Unable to locate parent package [json-package] for [class com.you.action.ColumnAction] -

    1.错误叙述性说明 三月 15, 2015 7:53:25 下午 com.opensymphony.xwork2.util.logging.jdk.JdkLogger error 严重: Dispat ...

  4. ORACLE在表中添加的目光凝视和读取列

    在ORACLE中给表.列添加凝视以及读取凝视 1.给表填加凝视:SQL>comment on table 表名 is '表凝视"; 2.给列加凝视:SQL>comment on ...

  5. sql小总结

    ---------------------------------------------------------------------------------------------------- ...

  6. docker study

    Author:Hyphen 同步公布在个人博客中:http://yanheven.github.io/docker-study/ 參考章宇兄的开源项目学习ABC的方法来对docker进行简单的学习与分 ...

  7. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(13)-权限设计

    原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(13)-权限设计 ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   (1):框架搭建    (2):数据 ...

  8. S2SH新手框架建立具体过程

    S2SH集成框架新手学习总结 第一章:S2SH框架新手搭建准备工作仅仅都须要导入那些文件 第二篇:S2SH框架新手搭建具体过程 版本号信息:Struts2.3+Hibernate4.3.6+Sprin ...

  9. JS里写入(混写)php asp

    原文:JS里写入(混写)php asp JS里写入(混写)php 方法1:<Br> <script language="javascript"> docum ...

  10. 【LeetCode】 sort list 单清单归并

    称号:Sort a linked list in O(n log n) time using constant space complexity. 思路:要求时间复杂度O(nlogn) 知识点:归并排 ...