HTTP GET Request Status 204 Vs 404
Asked Answered
C

6

64

I have 2 resources User and Album. A user has a list of albums. To get albums there are 2 REST API.

  1. user/{userId}/albums/{albumId} gets album by albumId. If not found returns 404
  2. user/{userId}/albums gets all albums by userId. In this case, if a user has no albums, what should be the status code 204 or 404?
Cowart answered 16/12, 2015 at 12:25 Comment(0)
B
68

Is the absence of any album really seen as an error? Assuming the albums are returned as a JSON array, the common response to such a situation would be a HTTP 200 with an empty array as the body.

Returning 404 signals that the resource doesn't exist, kind of saying that it isn't even possible to ask for the list of albums for this particular user. But in fact, it's possible to successfully return the list of albums, it's just that the list is empty. It doesn't seem at all exceptional to me. This is completely in contrast to retrieval of one specific album using an ID that doesn't exist (using your other endpoint); in such a situation a 404 is correct.

While a 204 seems better than a 404, because it at least tells the client that the request was successful but had no content, its intention is not really to be used to signal a "successful absence". Rather, it signals that the resource DOES exist but for some reason the server chose not to include the resource in the response body - for example the purpose of the request could have been to simply pass back some headers to the client.

A 204 can also be used as a response to a POST request where some action was carried out by the server without necessarily creating any new resource (which would have implied a 201 CREATED), or where it's for some other reason not relevant to return any resource.

I think it's clear that what you need is a

GET /user/xxx/albums

HTTP/1.1 200 OK

[]
Boydboyden answered 2/2, 2016 at 9:19 Comment(6)
200 means the request succeeded and there is data in the response. In this case there was no data in the response so 204 is actually the correct status code to return. Now if you called GET /user/xxx/albums, where xxx was a user that doesn't exist, I would then return a 404 with a message saying what resource wasn't found. Since this is a GET, there is no confusion with the typical scenario where you receive 204 for a POST. At the end of the day your API should have documentation telling the developer what status code mean what for a particular request.Nert
I disagree. There is data, an empty array. IMHO, it would be really strange to force the client to treat a perfectly valid query for a list - that momentarily happens to be empty - as an error, so we agree that 404 is excluded. However, 204 to me has a special use for where the client actually does not want or cannot be given any resource. Most apis I've ever seen would use an empty array, I don't see why it would be in any way controversial. Would you prefer null over empty lists in normal client side programming?Boydboyden
Yeah sorry I was updating my answer while you responded. Initial comment was too quick...Boydboyden
I see what you're saying. I guess instead of returning 200 with an empty array I typically choose to return 204 with nothing in the response body.Nert
The one thing that should never happen is to return 200 with validation errors, other than that returning empty sets is fine as this follows what user wants.Gavrila
I think 204 isn't the best response for no albums found because it forces the consumer to make special arrangements for that status code. If it's a 200 with empty array, their most common happy path can remain as is: arrayItem => doSomething(), It will never do something if empty. I know there is a separations between http protocols and consumer logic, but I think the codes should serve the consumers, not make it harderPhilippians
M
33

Here is what the RFC2616 that defines the HTTP protocol says about Status-codes:

The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role. There are 5 values for the first digit:

  - 1xx: Informational - Request received, continuing process

  - 2xx: Success - The action was successfully received,
    understood, and accepted

  - 3xx: Redirection - Further action must be taken in order to
    complete the request

  - 4xx: Client Error - The request contains bad syntax or cannot
    be fulfilled

  - 5xx: Server Error - The server failed to fulfill an apparently
    valid request

In your case, the request was successful, but there are no albums to show, so you definitely should use a status from the 2xx category.

Here is what the RFC says about the 204 status:

10.2.5 204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

The RFC states that the 204 is primarily intended to allow inputs, so you shouldn't use this one. I would use the 200 in this case.

Morning answered 12/7, 2017 at 2:43 Comment(2)
It is worth considering the case where a previous request for all of the user's albums has returned content, which will now be cached. If all of that user's albums are then removed, returning 204 to a subsequent request for the user's album list will tell the user agent "it SHOULD NOT change its document view from that which caused the request to be sent" - so the client's view of the album list will not reflect an empty list.Hardman
I just wish there was never a 204 for this scenario - it would have kept things simple. An empty response with a 200 would have sufficed. And BTW, why does a rest api have to care about whether the consumer's view has to change or not. The rest api's return codes should only allow consumers to clearly interpret the state of a resource, not define what the clients view should transition to.Vassalize
V
23

Error Code 404

The web site hosting server will typically generate a "404 Not Found" web page when a user attempts to follow a broken or dead link.

Return Code 204

The server has fulfilled the request but does not need to return an entity-body.

Conclusion

You obviously need to return a 204 status code. If you use the 404 one, the user may be disturbed. More, you use 404 when the targeted album doesn't exist. Using 404 for both 1 and 2 is illogical.

Visitor answered 16/12, 2015 at 12:36 Comment(2)
Either that or an empty JSON object -- if JSON applies.Eurus
So a Rest Api Endpoint will never return 404 because the routing is defined by hand? 404 will only be raised by the Server in case you use a url that is not defined by your api or is not available in case of a distrubited system.Mears
S
8

When you ask for a specific resource, say a user, and the user doesn't exist, then you should return 404. For example, you have an API to retrieve a user using the following URL:

https://yourdomain.com/api/users/:userid

and a request is made to retrieve user 1234, that doesn't exist, then you should return 404. In this case, the client requested a resource that doesn't exist.

https://yourdomain.com/api/users/1234 
404

Now suppose you have an api that returns all users in the system using the following url:

https://yourdomain.com/api/users

If there are no users in the system, then, in this case, you should return 204.

Sago answered 23/7, 2020 at 18:20 Comment(2)
Well put. Thank you.Obi
Wrong, the server could understand the resource you were trying to access, it could understand which process based on URI, so, no 404 should be used.Grass
P
7

Let me give my 2 cents on this. I hope you already know the difference between 404 vs 204. The scenario i would prefer to use each status code are :

404 Status Code

404 means that the Resource not found or doesn't exist or URL is invalid

For example

GET : https://api.myapp.io/product/product_id_123
GET : https://api.myapp.io/image/nokia.jpg

If the single product / resource item doesn't exist in database or in resource folder, that means the resource of this URL is invalid so we have to throw 404 and Search Engines like Google & bing will not going to cache the result and will not retry again the next day for fresh content.

204 Status Code

204 means that the URL is valid and Server has successfully did the execution but it has no data to return.

For example

GET : https://api.myapp.io/product/search?keyword=nokia

If there is no data matched (single or multiple) for the keyword in database to return back the results, then throw 204 because there is no data to return but the URL is still valid and Search Engines like Google & bing will retry again the next day for fresh content because for them it is not invalid url and when you retry the next day there might be some data which matches the query.

Polenta answered 24/12, 2021 at 20:6 Comment(1)
That makes total sense, thank you.Sloane
P
0

I agree with the responses, but I think is 204 or 200, it depends of your response when the album list is empty.

If you will return a empty array, the return it with 200 code, if you prefer to don't return anything, then the right one will be 204. (I prefer a 200 with empty list)

Only use 404 with a resource doesn't existis, if it is a empty list the choose 204 or 200.

Good hacking man!

Patriliny answered 1/11, 2020 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.