Let’s say you want to get list of users by calling GET to api/users, but currently the table was truncated so there are no users. What is the proper response for this scenario: 404 or 204?
Let’s say you want to get list of users by calling GET to api/users
Share
I’d say, neither.
Why not 404 (Not Found) ?
The 404 status code should be reserved for situations, in which a resource is not found. In this case, your resource is a collection of users. This collection exists but it’s currently empty. Personally, I’d be very confused as an author of a client for your application if I got a
200one day and a404the next day just because someone happened to remove a couple of users. What am I supposed to do? Is my URL wrong? Did someone change the API and neglect to leave a redirection.Why not 204 (No Content) ?
Here’s an excerpt from the description of the 204 status code by w3c
While this may seem reasonable in this case, I think it would also confuse clients. A
204is supposed to indicate that some operation was executed successfully and no data needs to be returned. This is perfect as a response to aDELETErequest or perhaps firing some script that does not need to return data. In case ofapi/users, you usually expect to receive a representation of your collection of users. Sending a response body one time and not sending it the other time is inconsistent and potentially misleading.Why I’d use a 200 (OK)
For reasons mentioned above (consistency), I would return a representation of an empty collection. Let’s assume you’re using XML. A normal response body for a non-empty collection of users could look like this:
and if the list is empty, you could just respond with something like this (while still using a
200):Either way, a client receives a response body that follows a certain, well-known format. There’s no unnecessary confusion and status code checking. Also, no status code definition is violated. Everybody’s happy.
You can do the same with JSON or HTML or whatever format you’re using.