Response status code for searches in REST APIs

The proper status code for each situation

Consider the following situations:

  • GET /api/guests?name=dummy

It’s an operation that requests a representation of a collection. If no items match the search criteria, return a 200 status code with an empty array in the response body, indicating that the request was successfully received, understood, and accepted by the server, and collection itself exists but the search returned no results.

  • GET /api/guests/{id}

It’s an operation that requests representation of a single resource using its unique identifier. If no resource was found return a 404 error, indicating that the server did not find the resource with that identifier.

More details

Have a look at the status code definitions in the RFC 7231 (which updates the old RFC 2616). It’s pretty clear:

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.

[…]

The HTTP status codes are organized in classes. Have a look at this:

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.

[…]

Leave a Comment