For example, there's a restful API GET http://luexu.com/users/{page}
to list the users in Nth page. Suppose there're 20 users in each page. There're 100 users total in the database. GET http://luexu.com/users/5
returns the 80th to 100th users.
So how about query GET http://luexu.com/users/10
? it's out of the total users. Which is a better design to return an empty list, empty array []
or 404
?
200?
{
"code": 200,
"msg": "OK",
"data": []
}
or 204?
{
"code": 204,
"msg": "OK",
"data": []
}
or 404?
{
"code": 404,
"msg": "Not Found",
"data": null
}
so how about code 204?
In HTTP, 204 No Content means something very specific -- that the message body is zero bytes long.
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.
So you shouldn't be thinking about it if you are sending, for example, a json encoded document.
If an empty list is an acceptable representation of the resource, then using 200
as the response code is fine. For instance, consider this URI for stack overflow itself.
As of 2019-06-01, there are many fewer than 999 pages of questions with these tags, but the server has no problem computing the correct representation for this page (including the information that the highest numbered page is 426). Therefore, the semantics of 200
are perfectly suitable.
404
means that no representation for the resource was available. All 4xx
class response codes indicate an error with the request -- in this case, it suggests that the client made a mistake with the URI. That could be a temporary condition (you shouldn't be asking about that resource right now). So that could also be fine, if what you want to indicate is that the client has left the happy path of the domain protocol.
How to choose? I start from this observation in the HTTP specification
the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
So which is useful to the client? A representation of the problem, or a representation of an empty collection? This can be a challenging question when the same resources are being used for different things.