2017-04-25 29 views
1

我們正在編寫一個REST API,它將公開暴露並被很多第三方開發人員使用。我正在查看http狀態碼的最佳做法,特別是在錯誤情況下。REST API Http狀態代碼最佳實踐

我們的應用程序在內部有很多組件,API是接口。如果內部組件有任何錯誤,我是否應該返回一個帶有適當錯誤信息的500?

通過SO時,我發現一些博客/ SO線程提出了不同的方式,但沒有一個具體答案。

對此非常感謝。

回答

3

這是非常主觀的。這是我的觀點,寫了幾個適度複雜的API。

認識到HTTP狀態代碼不會整齊地映射到您的內部組件將返回的錯誤種類。他們不是爲了。

遵循的基本規則是200是OK,其他都是錯誤。

我基本上只用這4個非正常狀態代碼:

400 =錯誤的請求。調用者發送了無效的請求參數。 401 =未經授權。來電者沒有權限提出請求。 404 =未找到。調用者請求了一個無法找到或不存在的資源。 500 =內部服務器錯誤。其他一切。發生了一些不好的事情,呼叫者可能無法做任何事情。

這就是HTTP狀態碼,就我而言。

但我並不止於此。我總是返回一個包含我自己的錯誤代碼,消息和 - 在測試環境中的JSON響應 - 堆棧跟蹤。我的錯誤代碼是一個呼叫者可以根據需要編程的數字。就我而言,這是真正的錯誤代碼。

+0

感謝您對@Mike的看法。我們正在按照您在此處列出的內容採用類似的方法。很高興知道我們處於正確的方向。 – M22an

1

以下是最佳API實踐的代碼列表。

codes = Array(
      100 => 'Continue', 
      101 => 'Switching Protocols', 
      200 => 'OK', 
      201 => 'Created', 
      202 => 'Accepted', 
      203 => 'Non-Authoritative Information', 
      204 => 'No Content', 
      205 => 'Reset Content', 
      206 => 'Partial Content', 
      300 => 'Multiple Choices', 
      301 => 'Moved Permanently', 
      302 => 'Found', 
      303 => 'See Other', 
      304 => 'Not Modified', 
      305 => 'Use Proxy', 
      306 => '(Unused)', 
      307 => 'Temporary Redirect', 
      400 => 'Bad Request', 
      401 => 'Unauthorized', 
      402 => 'Payment Required', 
      403 => 'Forbidden', 
      404 => 'Not Found', 
      405 => 'Method Not Allowed', 
      406 => 'Not Acceptable', 
      407 => 'Proxy Authentication Required', 
      408 => 'Request Timeout', 
      409 => 'Conflict', 
      410 => 'Gone', 
      411 => 'Length Required', 
      412 => 'Precondition Failed', 
      413 => 'Request Entity Too Large', 
      414 => 'Request-URI Too Long', 
      415 => 'Unsupported Media Type', 
      416 => 'Requested Range Not Satisfiable', 
      417 => 'Expectation Failed', 
      500 => 'Internal Server Error', 
      501 => 'Not Implemented', 
      502 => 'Bad Gateway', 
      503 => 'Service Unavailable', 
      504 => 'Gateway Timeout', 
      505 => 'HTTP Version Not Supported' 
     ); 
+0

感謝您提供完整的狀態碼參考。 – M22an

0

最有用的請求狀態代碼:

  • 碼100:信息
  • 碼200:成功
  • 碼300:重定向
  • 碼400:客戶端錯誤
  • 代碼500:服務器錯誤