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
  • 測試用 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM