'What should the response status code be in a REST API when the given ID is a valid ID but there's no matching document?

I'm using MongoDB for my Express app and I know that when an ID is an invalid ID for the corresponding database, the response status code is 400 (Bad Request). But what if the ID is a valid ID but there's no document with that ID (for example the document might be deleted)? I'm guessing the status code should be 404 but I'm not sure, what are your opinions?



Solution 1:[1]

What should the response status code be in a REST API when the given ID is a valid ID but there's no matching document?

404

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.

If you need to communicate why you are returning a 404, that's done in the body of the response:

the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.


Why not 204?

Primarily because that's not what 204 is for:

The 204 response allows a server to indicate that the action has been successfully applied to the target resource, while implying that the user agent does not need to traverse away from its current "document view" (if any).

For a GET request, the appropriate way to signal that the current representation is 0 bytes long is a 200 response with a Content-Length field.

That said, the origin server has the freedom to decide for itself whether the absence of a document with the right id means there is no current representation, or if the current representation is empty. In other words, the existence of "documents" at the origin server is an implementation detail that is hidden behind the web facade.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VoiceOfUnreason