HTTP Status code in REST API

请求方式 HTTP Methods

HTTP methods are sometimes referred to as HTTP verbs. They are simply just different ways to communicate via HTTP. The main ones used by the REST API are:

  • GET should be used for retrieving data from the API.
  • POST should be used for creating new resources (i.e users, products, taxonomies).
  • PUT should be used for updating resources.
  • DELETE should be used for deleting resources.
  • OPTIONS should be used to provide context about our resources.

HTTP status code

在访问REST API时,有时可能会遇到错误。有可能的类型:

错误代码Error Type
400 Bad RequestInvalid request, e.g. using an unsupported HTTP method

1、语义有误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求。
2、请求参数有误。
401 UnauthorizedAuthentication or permission error, e.g. incorrect API keys

当前请求需要用户验证。该响应必须包含一个适用于被请求资源的 WWW-Authenticate 信息头用以询问用户信息。客户端可以重复提交一个包含恰当的 Authorization 头信息的请求。如果当前请求已经包含了 Authorization 证书,那么401响应代表着服务器验证已经拒绝了那些证书。如果401响应包含了与前一个响应相同的身份验证询问,且浏览器已经至少尝试了一次验证,那么浏览器应当向用户展示响应中包含的实体信息,因为这个实体信息中可能包含了相关诊断信息。参见RFC 2617。
403 Forbidden服务器已经理解请求,但是拒绝执行它。与401响应不同的是,身份验证并不能提供任何帮助,而且这个请求也不应该被重复提交。如果这不是一个 HEAD 请求,而且服务器希望能够讲清楚为何请求不能被执行,那么就应该在实体内描述拒绝的原因。当然服务器也可以返回一个404响应,假如它不希望让客户端获得任何信息。

The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client’s identity is known to the server.
404 Not Found请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下。出现这个错误的最有可能的原因是服务器端没有这个页面。

Requests to resources that don’t exist or are missing
500 Internal Server Error服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器端的源代码出现错误时出现。

Server error

错误返回适当的HTTP状态代码和包含代码、消息和数据属性的响应对象。

Error Response

Login failed

{
  code: "jwt_auth_failed",
  message: "Invalid Credentials.",
  data: {
    status: 403
  }
}

Unauthorized

{
    code: "rest_cannot_get_products",
    message: "Sorry, You can not get products",
    data: {
        status: 401
    }
}

Content not found

{
  code: "product_not_found",
  message: "This is bottom line.",
  data: {
    status: 404
  }
}