# 快速入門
Yii 提供了一整套用來簡化實現 RESTful 風格的 Web Service 服務的 API。 特別是,Yii 支持以下關于 RESTful 風格的 API:
* 支持?[Active Record](http://www.yiichina.com/doc/guide/2.0/db-active-record)?類的通用API的快速原型
* 涉及的響應格式(在默認情況下支持 JSON 和 XML)
* 支持可選輸出字段的定制對象序列化
* 適當的格式的數據采集和驗證錯誤
* 支持?[HATEOAS](http://en.wikipedia.org/wiki/HATEOAS)
* 有適當HTTP動詞檢查的高效的路由
* 內置`OPTIONS`和`HEAD`動詞的支持
* 認證和授權
* 數據緩存和HTTP緩存
* 速率限制
如下, 我們用一個例子來說明如何用最少的編碼來建立一套RESTful風格的API。
假設你想通過 RESTful 風格的 API 來展示用戶數據。用戶數據被存儲在用戶DB表, 你已經創建了 yii\db\ActiveRecord 類`app\models\User`?來訪問該用戶數據.
## 創建一個控制器
首先,創建一個控制器類?`app\controllers\UserController`?如下,
~~~
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
~~~
控制器類擴展自 yii\rest\ActiveController。通過指定 yii\rest\ActiveController::modelClass 作為?`app\models\User`, 控制器就能知道使用哪個模型去獲取和處理數據。
## 配置URL規則
然后,修改有關在應用程序配置的`urlManager`組件的配置:
~~~
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
]
~~~
上面的配置主要是為`user`控制器增加一個 URL 規則。這樣, 用戶的數據就能通過美化的 URL 和有意義的 http 動詞進行訪問和操作。
## 嘗試
隨著以上所做的最小的努力,你已經完成了創建用于訪問用戶數據 的 RESTful 風格的 API。你所創建的 API 包括:
* `GET /users`: 逐頁列出所有用戶
* `HEAD /users`: 顯示用戶列表的概要信息
* `POST /users`: 創建一個新用戶
* `GET /users/123`: 返回用戶 123 的詳細信息
* `HEAD /users/123`: 顯示用戶 123 的概述信息
* `PATCH /users/123`?and?`PUT /users/123`: 更新用戶123
* `DELETE /users/123`: 刪除用戶123
* `OPTIONS /users`: 顯示關于末端?`/users`?支持的動詞
* `OPTIONS /users/123`: 顯示有關末端?`/users/123`?支持的動詞
> 補充:Yii 將在末端使用的控制器的名稱自動變為復數。(譯注:個人感覺這里應該變為注意)
你可以訪問你的API用`curl`命令如下,
~~~
$ curl -i -H "Accept:application/json" "http://localhost/users"
HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By: PHP/5.4.20
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
<http://localhost/users?page=2>; rel=next,
<http://localhost/users?page=50>; rel=last
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
[
{
"id": 1,
...
},
{
"id": 2,
...
},
...
]
~~~
試著改變可接受的內容類型為`application/xml`,你會看到結果以 XML 格式返回:
~~~
$ curl -i -H "Accept:application/xml" "http://localhost/users"
HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By: PHP/5.4.20
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
<http://localhost/users?page=2>; rel=next,
<http://localhost/users?page=50>; rel=last
Transfer-Encoding: chunked
Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8"?>
<response>
<item>
<id>1</id>
...
</item>
<item>
<id>2</id>
...
</item>
...
</response>
~~~
> 技巧:你還可以通過 Web 瀏覽器中輸入 URL?`http://localhost/users`?來訪問你的 API。 盡管如此,你可能需要一些瀏覽器插件來發送特定的 headers 請求。
如你所見,在 headers 響應,有關于總數,頁數的信息,等等。 還有一些鏈接,讓你導航到其他頁面的數據。例如:`http://localhost/users?page=2`?會給你的用戶數據的下一個頁面。
使用?`fields`?和?`expand`?參數,你也可以指定哪些字段應該包含在結果內。 例如:URL?`http://localhost/users?fields=id,email`?將只返回?`id`?和?`email`?字段。
> 補充:你可能已經注意到了?`http://localhost/users`?的結果包括一些敏感字段, 例如?`password_hash`,?`auth_key`?你肯定不希望這些出現在你的 API 結果中。 你應該在?[響應格式](http://www.yiichina.com/doc/guide/2.0/rest-response-formatting)?部分中過濾掉這些字段。
## 總結
使用 Yii 框架的 RESTful 風格的 API, 在控制器的操作中實現API末端,使用 控制器來組織末端接口為一個單一的資源類型。
從 yii\base\Model 類擴展的資源被表示為數據模型。 如果你在使用(關系或非關系)數據庫,推薦你使用 yii\db\ActiveRecord 來表示資源。
你可以使用 yii\rest\UrlRule 簡化路由到你的 API 末端。
為了方便維護你的WEB前端和后端,建議你開發接口作為一個單獨的應用程序,雖然這不是必須的。
- 介紹(Introduction)
- 關于 Yii(About Yii)
- 從 Yii 1.1 升級(Upgrading from Version 1.1)
- 入門(Getting Started)
- 安裝 Yii(Installing Yii)
- 運行應用(Running Applications)
- 第一次問候(Saying Hello)
- 使用 Forms(Working with Forms)
- 玩轉 Databases(Working with Databases)
- 用 Gii 生成代碼(Generating Code with Gii)
- 更上一層樓(Looking Ahead)
- 應用結構(Application Structure)
- 結構概述(Overview)
- 入口腳本(Entry Scripts)
- 應用(Applications)
- 應用組件(Application Components)
- 控制器(Controllers)
- 模型(Models)
- 視圖(Views)
- 模塊(Modules)
- 過濾器(Filters)
- 小部件(Widgets)
- 前端資源(Assets)
- 擴展(Extensions)
- 請求處理(Handling Requests)
- 運行概述(Overview)
- 引導(Bootstrapping)
- 路由引導與創建 URL(Routing and URL Creation)
- 請求(Requests)
- 響應(Responses)
- Sessions and Cookies
- 錯誤處理(Handling Errors)
- 日志(Logging)
- 關鍵概念(Key Concepts)
- 組件(Components)
- 屬性(Properties)
- 事件(Events)
- 行為(Behaviors)
- 配置(Configurations)
- 別名(Aliases)
- 類自動加載(Class Autoloading)
- 服務定位器(Service Locator)
- 依賴注入容器(Dependency Injection Container)
- 配合數據庫工作(Working with Databases)
- 數據庫訪問(Data Access Objects): 數據庫連接、基本查詢、事務和模式操作
- 查詢生成器(Query Builder): 使用簡單抽象層查詢數據庫
- 活動記錄(Active Record): 活動記錄對象關系映射(ORM),檢索和操作記錄、定義關聯關系
- 數據庫遷移(Migrations): 在團體開發中對你的數據庫使用版本控制
- Sphinx
- Redis
- MongoDB
- ElasticSearch
- 接收用戶數據(Getting Data from Users)
- 創建表單(Creating Forms)
- 輸入驗證(Validating Input)
- 文件上傳(Uploading Files)
- 收集列表輸入(Collecting Tabular Input)
- 多模型同時輸入(Getting Data for Multiple Models)
- 顯示數據(Displaying Data)
- 格式化輸出數據(Data Formatting)
- 分頁(Pagination)
- 排序(Sorting)
- 數據提供器(Data Providers)
- 數據小部件(Data Widgets)
- 操作客戶端腳本(Working with Client Scripts)
- 主題(Theming)
- 安全(Security)
- 認證(Authentication)
- 授權(Authorization)
- 處理密碼(Working with Passwords)
- 客戶端認證(Auth Clients)
- 安全領域的最佳實踐(Best Practices)
- 緩存(Caching)
- 概述(Overview)
- 數據緩存(Data Caching)
- 片段緩存(Fragment Caching)
- 分頁緩存(Page Caching)
- HTTP 緩存(HTTP Caching)
- RESTful Web 服務
- 快速入門(Quick Start)
- 資源(Resources)
- 控制器(Controllers)
- 路由(Routing)
- 格式化響應(Response Formatting)
- 授權驗證(Authentication)
- 速率限制(Rate Limiting)
- 版本化(Versioning)
- 錯誤處理(Error Handling)
- 開發工具(Development Tools)
- 調試工具欄和調試器(Debug Toolbar and Debugger)
- 使用 Gii 生成代碼(Generating Code using Gii)
- TBD 生成 API 文檔(Generating API Documentation)
- 測試(Testing)
- 概述(Overview)
- 搭建測試環境(Testing environment setup)
- 單元測試(Unit Tests)
- 功能測試(Functional Tests)
- 驗收測試(Acceptance Tests)
- 測試夾具(Fixtures)
- 高級專題(Special Topics)
- 高級應用模版(Advanced Project Template)
- 從頭構建自定義模版(Building Application from Scratch)
- 控制臺命令(Console Commands)
- 核心驗證器(Core Validators)
- 國際化(Internationalization)
- 收發郵件(Mailing)
- 性能優化(Performance Tuning)
- 共享主機環境(Shared Hosting Environment)
- 模板引擎(Template Engines)
- 集成第三方代碼(Working with Third-Party Code)
- 小部件(Widgets)
- Bootstrap 小部件(Bootstrap Widgets)
- jQuery UI 小部件(jQuery UI Widgets)
- 助手類(Helpers)
- 助手一覽(Overview)
- Array 助手(ArrayHelper)
- Html 助手(Html)
- Url 助手(Url)