前不久做一個項目,是用Yii2框架寫一套RESTful風格的API,就去查了下《Yii 2.0 權威指南 》,發現上面寫得比較簡略。所以就在這里寫一篇教程貼,希望幫助剛接觸Yii2框架RESTful的小伙伴快速入門。
一、目錄結構
實現一個簡單地RESTful API只需用到三個文件。目錄如下:
frontend
├─ config
│ └ main.php
├─ controllers
│ └ BookController.php
└─ models
└ Book.php
二、配置URL規則
1.修改服務器的rewrite規則,將所有URL全部指向index.php上,使其支持 /books/1 格式。
如果是Apache服務器,在frontend/web/ 目錄中新建.htaccess文件。文件內容如下:
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
如果是Nginx服務器,修改nginx/conf/nginx.conf,在當前"server{}"的"location / {}"中添加下面紅色標記內容:
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
2.修改frontend/config/main.php文件,為book控制器增加一個 URL 規則。這樣,就能通過美化的 URL 和有意義的 http 動詞進行訪問和操作數據。配置如下:
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'book'],
],
],
],
三、創建一個model
1.在數據庫中創建一張book表。book表的內容如下:
-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` char(50) NOT NULL DEFAULT '',
`num` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES ('1', 'toefl', '10');
INSERT INTO `book` VALUES ('2', 'ielts', '20');
INSERT INTO `book` VALUES ('3', 'sat', '30');
INSERT INTO `book` VALUES ('4', 'gre', '40');
INSERT INTO `book` VALUES ('5', 'gmat', '50');
2.在frontend/models/目錄中新建Book.php。文件內容如下:
namespace frontend\models;
use yii\db\ActiveRecord;
class Book extends ActiveRecord
{
public static function tableName()
{
return 'book';
}
}
四、創建一個控制器
在frontend/controllers/目錄中新建BookController.php。控制器類擴展自 yii\rest\ActiveController。通過指定 yii\rest\ActiveController::modelClass 作為 frontend\models\Book, 控制器就能知道使用哪個模型去獲取和處理數據。文件內容如下:
namespace frontend\controllers;
use yii\rest\ActiveController;
class BookController extends ActiveController
{
public $modelClass = 'frontend\models\Book';
}
五、測試
到這里,我們就已經完成了創建用於訪問用戶數據 的 RESTful 風格的 API。創建的 API 包括:
GET /books: 列出所有的書 HEAD /books: 顯示書的列表的概要信息 POST /books: 新增1本書 GET /books/1: 返回 書ID=1的詳細信息 HEAD /books/1: 顯示 書ID=1的概述信息 PATCH /books/1 and PUT /books/1: 更新書ID=1的信息 DELETE /books/1: 刪除書ID=1的信息 OPTIONS /books: 顯示關於末端 /books 支持的動詞 OPTIONS /books/1: 顯示有關末端 /books/1 支持的動詞
可以通過Web瀏覽器中輸入 URL http://{frontend的域名}/books 來訪問API,或者使用一些瀏覽器插件來發送特定的 headers 請求,比如Firefox的RestClient、Chrome的Advanced Rest Client、postman等。
六、說明
1.Yii 將在末端使用的控制器的名稱自動變為復數。這是因為 yii\rest\UrlRule 能夠為他們使用的末端全自動復數化控制器。可以通過設置yii\rest\UrlRule::pluralize為false來禁用此行為:
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'book', 'pluralize' => false],
],
2.可以使用fields和expand參數指定哪些字段應該包含在結果內。例如:URL http://{frontend的域名}/books?fields=name,num 將只返回 name 和 num 字段。
今天接着來探究一下Yii2 RESTful的格式化響應,授權認證和速率限制三個部分
一、目錄結構
先列出需要改動的文件。目錄如下:
web
├─ common
│ └─ models
│ └ User.php
└─ frontend
├─ config
│ └ main.php
└─ controllers
└ BookController.php
二、格式化響應
Yii2 RESTful支持JSON和XML格式,如果想指定返回數據的格式,需要配置yii\filters\ContentNegotiator::formats屬性。例如,要返回JSON格式,修改frontend/controllers/BookController.php,加入紅色標記代碼:
namespace frontend\controllers;
use yii\rest\ActiveController;
use yii\web\Response;
class BookController extends ActiveController
{
public $modelClass = 'frontend\models\Book';
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
return $behaviors;
}
}
返回XML格式:FORMAT_XML。formats屬性的keys支持MIME類型,而values必須在yii\web\Response::formatters中支持被響應格式名稱。
三、授權認證
RESTful APIs通常是無狀態的,因此每個請求應附帶某種授權憑證,即每個請求都發送一個access token來認證用戶。
1.配置user應用組件(不是必要的,但是推薦配置):
設置yii\web\User::enableSession屬性為false(因為RESTful APIs為無狀態的,當yii\web\User::enableSession為false,請求中的用戶認證狀態就不能通過session來保持)
設置yii\web\User::loginUrl屬性為null(顯示一個HTTP 403 錯誤而不是跳轉到登錄界面)
具體方法,修改frontend/config/main.php,加入紅色標記代碼:
'components' => [
...
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'enableSession' => false,
'loginUrl' => null,
],
...
]
2.在控制器類中配置authenticator行為來指定使用哪種認證方式,修改frontend/controllers/BookController.php,加入紅色標記代碼:
namespace frontend\controllers;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\QueryParamAuth;
class BookController extends ActiveController
{
public $modelClass = 'frontend\models\Book';
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
/*下面是三種驗證access_token方式*/
//1.HTTP 基本認證: access token 當作用戶名發送,應用在access token可安全存在API使用端的場景,例如,API使用端是運行在一台服務器上的程序。
//HttpBasicAuth::className(),
//2.OAuth 2: 使用者從認證服務器上獲取基於OAuth2協議的access token,然后通過 HTTP Bearer Tokens 發送到API 服務器。
//HttpBearerAuth::className(),
//3.請求參數: access token 當作API URL請求參數發送,這種方式應主要用於JSONP請求,因為它不能使用HTTP頭來發送access token
//http://localhost/user/index/index?access-token=123
QueryParamAuth::className(),
],
];
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
return $behaviors;
}
}
3.創建一張user表
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL DEFAULT '' COMMENT '用戶名',
`password_hash` varchar(100) NOT NULL DEFAULT '' COMMENT '密碼',
`password_reset_token` varchar(50) NOT NULL DEFAULT '' COMMENT '密碼token',
`email` varchar(20) NOT NULL DEFAULT '' COMMENT '郵箱',
`auth_key` varchar(50) NOT NULL DEFAULT '',
`status` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '狀態',
`created_at` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '創建時間',
`updated_at` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新時間',
`access_token` varchar(50) NOT NULL DEFAULT '' COMMENT 'restful請求token',
`allowance` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'restful剩余的允許的請求數',
`allowance_updated_at` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'restful請求的UNIX時間戳數',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `access_token` (`access_token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin', '$2y$13$1KWwchqGvxDeORDt5pRW.OJarf06PjNYxe2vEGVs7e5amD3wnEX.i', '', '', 'z3sM2KZvXdk6mNXXrz25D3JoZlGXoJMC', '10', '1478686493', '1478686493', '123', '4', '1478686493');
在common/models/User.php類中實現 yii\web\IdentityInterface::findIdentityByAccessToken()方法。修改common/models/User.php,加入紅色標記代碼::
public static function findIdentityByAccessToken($token, $type = null)
{
//findIdentityByAccessToken()方法的實現是系統定義的
//例如,一個簡單的場景,當每個用戶只有一個access token, 可存儲access token 到user表的access_token列中, 方法可在User類中簡單實現,如下所示:
return static::findOne(['access_token' => $token]);
//throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
四、速率限制
為防止濫用,可以增加速率限制。例如,限制每個用戶的API的使用是在60秒內最多10次的API調用,如果一個用戶同一個時間段內太多的請求被接收,將返回響應狀態代碼 429 (這意味着過多的請求)。
1.Yii會自動使用yii\filters\RateLimiter為yii\rest\Controller配置一個行為過濾器來執行速率限制檢查。如果速度超出限制,該速率限制器將拋出一個yii\web\TooManyRequestsHttpException。
修改frontend/controllers/BookController.php,加入紅色標記代碼:
namespace frontend\controllers;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\RateLimiter;
class BookController extends ActiveController
{
public $modelClass = 'frontend\models\Book';
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['rateLimiter'] = [
'class' => RateLimiter::className(),
'enableRateLimitHeaders' => true,
];
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
/*下面是三種驗證access_token方式*/
//1.HTTP 基本認證: access token 當作用戶名發送,應用在access token可安全存在API使用端的場景,例如,API使用端是運行在一台服務器上的程序。
//HttpBasicAuth::className(),
//2.OAuth 2: 使用者從認證服務器上獲取基於OAuth2協議的access token,然后通過 HTTP Bearer Tokens 發送到API 服務器。
//HttpBearerAuth::className(),
//3.請求參數: access token 當作API URL請求參數發送,這種方式應主要用於JSONP請求,因為它不能使用HTTP頭來發送access token
//http://localhost/user/index/index?access-token=123
QueryParamAuth::className(),
],
];
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
return $behaviors;
}
}
2.在user表中使用兩列來記錄容差和時間戳信息。為了提高性能,可以考慮使用緩存或NoSQL存儲這些信息。
修改common/models/User.php,加入紅色標記代碼:
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\filters\RateLimitInterface;
class User extends ActiveRecord implements IdentityInterface, RateLimitInterface
{
....
// 返回在單位時間內允許的請求的最大數目,例如,[10, 60] 表示在60秒內最多請求10次。
public function getRateLimit($request, $action)
{
return [5, 10];
}
// 返回剩余的允許的請求數。
public function loadAllowance($request, $action)
{
return [$this->allowance, $this->allowance_updated_at];
}
// 保存請求時的UNIX時間戳。
public function saveAllowance($request, $action, $allowance, $timestamp)
{
$this->allowance = $allowance;
$this->allowance_updated_at = $timestamp;
$this->save();
}
....
public static function findIdentityByAccessToken($token, $type = null)
{
//throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
//findIdentityByAccessToken()方法的實現是系統定義的
//例如,一個簡單的場景,當每個用戶只有一個access token, 可存儲access token 到user表的access_token列中, 方法可在User類中簡單實現,如下所示:
return static::findOne(['access_token' => $token]);
}
....
}

