iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 17
1
Software Development

30天開發與部署 Laravel 專案系列 第 17

RESTful API (2) :Response

前言

個人認為 RESTful API的response除了json之外,也應讓人快速理解request後發生什麼事。因此本篇會從「格式」與「HTTP狀態碼」分別討論。

格式

個人習慣不管請求成功或失敗,都會提供固定格式的json給前端。

例如

//成功案例
return response()->json(['success' => true, 'message' => "add success", 'data' => $dataResult], 200);

//失敗案例
return response()->json(['success' => false, 'message' => $messageError, 'data' => null], 400); 

而非

//成功案例
return response()->json($dataResult), 200);

//失敗案例
return response()->json($messageError), 200);

固定回傳格式,對於強型別語言的編譯比較不會出錯。

未固定格式時,雖然可透過http status code判斷成功或失敗,但解析json又得多花一段心力或通靈,來預防未知的錯誤。

怎麼回傳格式,其實只要團隊討論好就行,google 「API response format 」可以發現有許多範例。若團隊無人有特殊要求,建議後端工程師可以先提出固定回傳格式的成功與失敗案例供團隊使用。例如這種寫法也是蠻好理解的:

//response of successful request:
{
  "status": "success",
  "data": {
    /* Application-specific data would go here. */
  },
  "message": null /* Or optional success message */
}
//response of failed request:
{
  "status": "error",
  "data": null, /* or optional error payload */
  "message": "Error xyz has occurred"
}

http status code

Laravel 的 Response Objects除了可自訂header之外,http status code也是可以自行設定的。

http status code,又稱HTTP狀態碼,使用3位數字來表示 web server在超文本傳輸協定的回應狀態,在RFC的分類下,主要有以下幾種 :

  • 1xx : 臨時資訊回應
  • 2xx : 成功回應
  • 3xx : 重新導向
  • 4xx : 客戶端請求錯誤
  • 5xx : 伺服器內部錯誤

個人常用的狀態碼如下

200 OK

  • 請求成功。
  • 用於CRUD的「R」、「U」

201 Created

  • 請求成功且新成功被創建data
  • 用於CRUD的「C」

202 Accepted

  • 此請求已經被接受但尚未處理

204 No Content

  • 伺服器成功處理了請求,沒有返回任何內容。
  • 可用於CRUD的「D」
  • There is no content to send for this request, but the headers may be useful.

400 Bad Request

  • 伺服器因為收到無效語法,而無法理解請求
  • 錯誤的參數格式,例如Laravel驗證應該要文字格式但非文字

401 Unauthorized

  • 401語意即「未認證」,即用戶沒有必要的憑據
  • 需要正確、可用、時效內的token以回應請求

403 Forbidden

  • 用戶端並無訪問權限,例如未被授權,所以伺服器拒絕給予應有的回應。
  • 不同於 401,伺服端知道用戶端的身份。

404 Not Found

  • Laravel路由錯誤會直接使用404

5xx

  • Laravel server異常也會直接使用5xx開頭

參考資料
https://noob.tw/restful-api/
https://zh.wikipedia.org/wiki/%E5%BC%B7%E5%BC%B1%E5%9E%8B%E5%88%A5
https://stackoverflow.com/questions/12806386/is-there-any-standard-for-json-api-response-format
https://docs.microsoft.com/zh-tw/azure/architecture/best-practices/api-design
https://tw.ews.mall.yahooapis.com/handbook_v3/webservice_guide/format/
https://learnku.com/docs/laravel/7.x/responses/7463
https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81
https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Status


上一篇
RESTful API (1) :Create
下一篇
RESTful API (3):Read/Update/Delete
系列文
30天開發與部署 Laravel 專案30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言