RESTful API 介紹及經驗分享

在現在系統開發,RESTful 無疑是 API 溝通的主流之一,在這裏,主要針對我個人對於 RESTful API 使用狀態及理解做一個分享。

REST 是一個設計風格,全名為 Representational State Transfer (表現層狀態轉換)是在 2000 年,由 Roy Thomas Fielding 所提出來的一種軟體架構風格,用於定義資源及管理資源。

RESTful 則是基於 REST 的一種設計風格,而不是原則!

一般API呼叫方式,主要可有兩部分:通訊協議及序列化

通訊協定是呼叫的連線方式,序列化則是返回資料的格式,常見有以下幾種:

通訊協議 - Http, Websocket, RPC..

序列化 - JSON, XML, Byte..

以 RESTful API 而言,最常見的組合為 Http + JSON,

RESTful 結構

在設計 RESTful API 時,通常有兩個重點: 將應用層定義為資源(resource),提供資源增刪改查功能

以下面這個例子來說,我們定義了一個 resource,並且為了跟 web 應用做區隔,另外再添加一個 api 層:

GET		 取得資源 <webservice>/api/product{?/id}
POST	 建立資源 <webservice>/api/product/{id}
PUT		 更新資源 <webservice>/api/product{id}
DELETE 	 刪除資源 <webservice>/api/product/{id}

針對取得資源,通常會在針對資源進行篩選,或者需要夾帶參數進行驗證,登入等行為,則可以這麼做

查詢

GET <webservice>/api/product?name=Adam&year=2020

登入:

POST <webservice>/api/login HTTP/1.1
Content-type: application/json

{
"username":"yourid",
"password":"yourpassword"
}

RESTful API 定義版號

通常,我在最初設計 API 時,並不會當下就提供版本號碼。

在軟體不斷迭代,不同版本軟體請求的API結構開始出現分隔時,才會做版號切割。

此時,會將最初的 API 定義為第一版,後續的版本才會在請求 resource 在添增一個版本號,以提供不同時期迭代版本的軟體使用,

例如:

<webservice>/api/v2/product

也可以用

<webservice>/api/product?version=2

並且在返回的 HEAD 附上版本

Custom-Header: api-version=2

序列化狀態

在透過通訊層,對資源進行操作後,伺服端需要返回操作狀態,讓客戶端理解這次的請求是否成功

關於序列化狀態,包含的層面相當廣泛,未來有機會再做介紹,這裡僅從大致方向做個說明。

通常格式會包含幾種內容:

  • 狀態
  • 狀態碼
  • 資料

回應狀態碼規則如下:

2xx  Success
3xx  Redirect
4xx  User error
5xx  Server error

常用的預設狀態碼有以下:

200: OK. The standard success code and default option. 201: Object created. Useful for the store actions. 204: No content. When an action was executed successfully, but there is no content to return. 206: Partial content. Useful when you have to return a paginated list of resources. 400: Bad request. The standard option for requests that fail to pass validation. 401: Unauthorized. The user needs to be authenticated. 403: Forbidden. The user is authenticated, but does not have the permissions to perform an action. 404: Not found. This will be returned automatically by Laravel when the resource is not found. 500: Internal server error. Ideally you’re not going to be explicitly returning this, but if something unexpected breaks, this is what your user is going to receive. 503: Service unavailable. Pretty self explanatory, but also another code that is not going to be returned explicitly by the application.

RESTful API Flow

最後,同樣是先簡單聊一下什麼是 RESTful API Flow,未來有機會再做補充。

在設計微服務架構時, RESTful API 應用,會包含更複雜的多服務溝通、快取機制、驗證機制等。

事實上,這部分已經涉及架構層面,

在這些複雜的架構,需要有資深的架構師來負責將 RESTful 將 API Flow 做有效的規劃,

基本上,在 API 的基礎,我們前面都有提過。

但關鍵就在於 resource ,如何將這些資源定義與管理,其實才是真正的重點。

今天就分享到這裡,如果對於 RESTful API 有興趣的朋友,也歡迎把你的想法告訴我。