RESTful API

George Chang
Jul 10, 2017 · 3 min read

REST (Representational state transfer) 是一個架構的設計風格,用這種風格設計出Web App,透過HTTP傳輸資料,而用這種風格設計的API就可以稱作RESTful API。

REST一共有6個設計要點

  1. Uniform Interface. 也就是說,你必須做成一個標準,一個SOP,像是透過URI去描述你可以存取的資料,例如/users或者/products。透過MIME types去描述存取資料時的資料格式。透過HTTP status code去描述請求成功或失敗的代碼。以及透過HTTP action去描述存取的動作是什麼。
  2. Client-server. 使用Client-server架構。
  3. Stateless. 也就是之前文章提到的HTTP特性,Client與Server每次溝通都是視為單一且獨立的請求,彼此不會有任何關聯。讓Server處理請求保持獨立性與簡潔。
  4. Cacheable. 利用快取來加快讀取速度並減少Server loading。
  5. Layered System. 可透過分層來達到關注點分離(separation of concerns)或者隱藏背後的執行步驟,例如Client透過ServerA存取API資源,由ServerA去存取放在ServerB的資料庫資料。
  6. Code-on-demand (optional). 意思是你可以將API設計成可回傳能執行的程式碼,例如Javascript。這麼做當然可以增強API的功能,目前很少有人這樣做。

在上述第一點提到的,REST用HTTP的action來表達以下動作

用GET來查詢資料

GET http://myserver.com/users #查詢所有使用者資料GET http://myserver.com/users/robin # 查詢robin的資料

用POST來建立資料

POST /users HTTP/1.1
Host: http://myserver.com
name=Robin&email=robin@gmail.com

用PUT來更新資料

PUT /users/robin HTTP/1.1
Host: http://myserver.com
email=robin@gmail.com

用DELETE來刪除資料

DELETE /users/robin HTTP/1.1
Host: http://myserver.com

這樣子設計出來的API變具有一致性,可以自我描述功能是什麼,使得開發人員更容易了解每個API的用途。而每次處理請求的獨立性讓它容易的達到水平擴展。

下一篇會講的是如何用framework建立一個RESTful API

origino

A Technical Organization in Taiwan

George Chang

Written by

Software Engineer

origino

origino

A Technical Organization in Taiwan

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade