14
REST & RESTful Scott

REST and RESTful

Embed Size (px)

Citation preview

Page 1: REST and RESTful

REST & RESTful

Scott

Page 2: REST and RESTful

Representational State Transfer

2000年Dr. Roy Fielding提出的博士論文

Page 3: REST and RESTful

REST是一種軟體設計架構風格

Page 4: REST and RESTful

REST Constraints

• Client-Server: 使用主從式架構設計• Stateless: 無狀態設計• Cacheable: 可實作快取• Uniform Interface: 一致性的介面

– Identification of resources: 唯一的資源識別– Manipulation of resources: 特定的操作方法來操作資源

– Self-descriptive messages: 自我描述資訊– Hypermedia as the engine of application state

• Layered System: 層級式架構• Code-On-Demand (optional): 如JavaScript

Page 5: REST and RESTful

What is RESTful ?

符合REST原則的系統架構,就稱RESTful

Page 6: REST and RESTful

設計RESTful Web Service

• 替Resource定義URI (Nouns)• 選擇適合的HTTP Method (Verbs)

Page 7: REST and RESTful

替Resource定義URI

舉例來說,API提供帳號、角色、團體的資訊,則URI會如下:• http://localhost/accounts• http://localhost/roles• http://localhost/groups

Page 8: REST and RESTful

選擇適合的HTTP Method

• GET:從Server取得資源,可以是一個或一個以上。

• POST:在Server上建立新資源。• PUT:更新Server上的資源。• DELETE:刪除Server上的資源。

Page 9: REST and RESTful

Http Method URI Description

GET /accounts 列出所有帳號

GET /accounts/{account_id} 取得指定帳號資料

POST /accounts 新增帳號

PUT /accounts/{account_id} 修改指定帳號資料

DELETE /accounts/{account_id} 刪除指定帳號資料

GET /accounts/{account_id}/roles 列出帳號的所有角色

GET /accounts/{account_id}/roles/{role_id} 取得帳號的指定角色資料

DELETE /accounts/{account_id}/roles/{role_id} 刪除帳號的指定角色資料

Page 10: REST and RESTful

其他實踐重點

• 使用HTTP Status Code處理錯誤• 為Resource Collection提供paging、

sorting、filtering• 為API版本化

Page 11: REST and RESTful

使用HTTP Status Code處理錯誤

HTTP Method Status Code Description

GET 200 (OK) 順利取得資源

400 (Bad Request) 無法順利取得資源,因為參數有問題或查尋條件失效

404 (Not Found) 資源不存在

POST 201 (Created) 成功新增資源

404 (Not Found) 資源不存在

PUT 200 (OK) 成功修改,並回傳異動後的資源

201 (Created) 成功修改資源

204 (No Content) 成功修改,但不回傳異動後的資源

404 (Not Found) 資源不存在

DELETE 200 (OK) 成功刪除,並回傳異動後的資源

204 (No Content) 成功刪除,但不回傳異動後的資源

404 (Not Found) 資源不存在

Page 12: REST and RESTful

為Resource Collection提供paging、sorting、filtering

以分頁舉例,我們要傳遞頁碼(pageNo)、每頁筆數(pageSize)資訊。假設我們要取得第二頁的十筆帳號。

其URI顯示如:/accounts?pageNo=2&pageSize=10

Page 13: REST and RESTful

為API版本化

• API版本變得強制性• 規則如/api/[version]/[resource name]

– [version]:使用”v”開頭,加上正整數

Page 14: REST and RESTful

Q & A