REST API 中搜索的响应状态代码

Response status code for searches in REST APIs

假设,我们有以下 API:

GET /api/guests/{id}
GET /api/guests?name=dummy

当没有客人符合条件时,我应该 return 哪个状态码?我的意思是没有名字为 dummy.

的客人

应该是404204还是200空数组?

我会 return 200 空数组...
或 204(无内容)

A 404 是指未找到 资源。 在这种情况下,您的资源是存在的来宾集合。

200 和空的项目列表。作为访客 ressource 通常 被发现 但它没有匹配您的查询的项目

每种情况的正确状态代码

考虑以下情况:

  • GET /api/guests?name=dummy

这是一个请求集合表示的操作。如果没有项目匹配搜索条件,return一个200响应体中空数组的状态码,表示请求被服务器成功接收、理解和接受,集合本身存在但搜索 return 没有结果。

  • GET /api/guests/{id}

这是一个请求使用其唯一标识符表示单个资源的操作。如果没有找到资源 return 一个 404 错误,表示服务器没有找到具有该标识符的资源。

更多详情

查看 RFC 7231 (which updates the old RFC 2616) 中的状态代码定义。很清楚:

6.3.1. 200 OK

The 200 (OK) status code indicates that the request has succeeded. The payload sent in a 200 response depends on the request method. For the methods defined by this specification, the intended meaning of the payload can be summarized as:

  • GET: a representation of the target resource;

  • HEAD: the same representation as GET, but without the representation data;

  • POST: a representation of the status of, or results obtained from, the action;

  • PUT, DELETE: a representation of the status of the action;

  • OPTIONS: a representation of the communications options;

  • TRACE: a representation of the request message as received by the end server.

[...]

6.3.5. 204 No Content

The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body. Metadata in the response header fields refer to the target resource and its selected representation after the requested action was applied.

[...]

6.5.4. 404 Not Found

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.

[...]

HTTP 状态代码组织在 类 中。看看这个:

6.3. Successful 2xx

The 2xx (Successful) class of status code indicates that the client's request was successfully received, understood, and accepted.

6.5. Client Error 4xx

The 4xx (Client Error) class of status code indicates that the client seems to have erred. Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

[...]