What's the most appropriate HTTP status code for an "item not found" error page
Asked Answered
D

10

201

I'm curious what's the most appropriate HTTP status code for an "item does not exist" page.

If the page itself doesn't exist, I'll obviously use 404. However, one of my pages has a userid argument (it's an "edit user" page) and in case no user with the given user ID exists I'm displaying an error page, but I'd also like to send a 4xx status header (since "200 OK" doesn't really fit).

I guess 404 would be ok since it's "not found" and not "file not found", but I wonder if there's a better code for this case.

Diffractive answered 9/4, 2011 at 11:44 Comment(0)
R
214

Getting overly clever with obscure-er HTTP error codes is a bad idea. Browsers sometimes react in unhelpful ways that obfuscate the situation. Stick with 404.

Rubato answered 9/4, 2011 at 11:47 Comment(6)
Damn you for giving good advice :( The OCD to not 404 all the things is real though.Tenpin
404 errors are somewhat ambiguous for differentiating a bad URI versus entity not found. A new standard code is needed to disambiguate 404s.Doncaster
I prefer returning 204 empty content than returning an ambigus status codeFirecrest
This article (kinsta.com/blog/http-status-codes) describes an HTTP code grouping of "200s: Codes returned when browser request was received, understood, and processed by the server." vs "400s: Codes indicating that there was a problem with the request". Based on that, to me it would seem that if the logic is successfully querying a database for something by ID and nothing was found for that ID there wasn't a "problem with the request", it was more "the successful query of data found no data matching the criteria", HTTP 204 seems more appropriate than HTTP 404.Orient
@Firecrest 204 is wrong as it is ment to use if the content currently displayed has not changed. Only some header fields might vary. I also used this status code as a lack of 404 differentiation. Overall, I would say the most important thing is to document which status code you use for each scenario. Also an apropriate error massage is always helpful.Madelynmademoiselle
this is wrong why would you 404 a user not found? you would return bad request with error and display error, for resources you would 404, engines are not going to be indexing userid requestsTannenwald
P
70

A 404 return code actually means 'resource not found', and applies to any entity for which a request was made but not satisfied. So it works equally-well for pages, subsections of pages, and any item that exists on the page which has a specific request to be rendered.

So 404 is the right code to use in this scenario. Note that it doesn't apply to 'server not found', which is a different situation in which a request was issued but not answered at all, as opposed to answered but without the resource requested.

Phrixus answered 9/4, 2011 at 11:51 Comment(2)
What if I want to update foo object with id=1 and there is no foo in the database with this id?Predator
In this scenario, you have a concurrency problem to fix: if you retrieved an object with id=1 and it no longer exists when you try to update it, some other thread or process ignored your lock (or you didn't set one) and deleted it. That's not good. Alternatively, if you're trying to update object id=n (where n is provided to you) without first checking it exists, you're missing a validation step in your update logic, which is also not good.Phrixus
B
36

204:

No Content.” This code means that the server has successfully processed the request, but is not going to return any content

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204

Belike answered 13/8, 2020 at 14:28 Comment(5)
"Item not found" is usually not a success, so I don't think a 2xx status code is appropriate.Diffractive
If you read carefully, will notice that it was taken from oficial content. Go access the url and remove this down vote plsBelike
I don't see anything on the MDN page that backs your claim that this is an appropriate response. I understand 204 as a response code for an action that does not need content, like having deleted something. Trying to get data for a user that does not exist is not a success.Diffractive
I like this answer. I believe the documentation in the link backs it up as well. In my scenario I have a dropdown list that pulls from one of two tables based on a toggle switch. If the initially selected value isn't available in the list after toggling, a 204 error code sounds like a solid way to indicate the condition.Yann
This means the overall status of the response is a success but the response is empty. Copied: 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).Downpipe
B
24

404 is just fine. HTTP Status Code Definitions from RFC9110

Bargainbasement answered 9/4, 2011 at 11:46 Comment(0)
K
13

That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like

400 (bad request) ‐ indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update

More info in free InfoQ Explores: REST book.

Kurtzig answered 9/4, 2011 at 11:54 Comment(1)
By saying "additional parameter" do you mean request header field? Otherwise I wouldn't recommend using 412. "The 412 (Precondition Failed) status code indicates that one or more conditions given in the request header fields evaluated to false when tested on the server."Giga
A
8

204 is the appropriate solution when the item is not found because the 404 status code will throw even uncreated APIs.

404 Status Code:

404 status code automatically appears when the requested API is unavailable. Links that lead to a 404 page are often called broken or dead links and can be subject to link rot.

204 Status Code:

204 status code should be when the item is not found which means your request processed successfully and the content not found.

Ahders answered 4/1, 2023 at 8:34 Comment(5)
No, 204 is not correct here at all. 204 simply means that the response has no content, e.g. because it was a request to delete something or trigger some action where there's no need to send anything but "it was successful" back to the client.Diffractive
404 will get even if the API is not available so there is no point to using 404Ahders
The specification says: The 204 response MUST NOT include a message-body. 204 should never be returned in response to a GET request in a REST API for a resource. The appropriated status is 404.Jijib
@Jijib for uncreated api also we will get the 404, so no point in using 404.Ahders
i agree with the answer. simply because you write with a big font, does not make you right on a clearly ambiguous situation..Buchanan
M
5

If the page itself doesn't exist, I'll obviously use 404.

What you said there is a bit confusing but I will have to assume that you're developing an API backend.

The problem is that whoever is consuming the API endpoint may be confused in two ways:

  1. They may think the 404 returned is because the endpoint(resource) wasn't reached, Or
  2. They might think that the item or user being requested wasn't found.

So the trick is, how are they going to know which is the right assumption?

Well, the answer is simple. Always try to attach a body to any errors that you returned from code. Errors that are returned by the server automatically do not have a body. So try to attach a body which you can document so that they can be able to use the content of the body to differentiate between code returned errors and server errors.

But in a nutshell, 404 is the right status to return, but try to attach a body to it indicating why 404 was returned.

An example could be:

// For illustration I'm just gonna use C#
Return NotFound(new { errorMessage: "Item requested was not found" });

Here, NotFound returns a 404 statuscode and the parameter is an object like { errorMessage: "some reason for the error"}. This way, you can always check if your error returned a body, and the you know it's returned from your code. Otherwise, the resource(link) wasn't found.

Mihe answered 21/7, 2021 at 17:24 Comment(0)
G
2

The previous answers lack nuance and yet require a lot of reading to understand the differences.

Rule of thumb:

  • 404 when the page or endpoint itself is missing
  • 404 when the endpoint is present and the query got properly processed, but produced no results AND THAT'S MEANT TO BE AN ERROR

(e.g. querying a user on its ID and you know the ID is supposed to exist)

  • 204 when the page is present and the query got properly processed but produced no results AND THAT'S OK

(e.g. searching users by date of birth and it just so happens that no user has this date of birth. That's not an error, an empty result is just one possible result -- and will just display an empty results table in the frontend)

204 is very nice for modern REST APIs ...But make sure that your frontend knows to tell the difference between 200 and 204 if that's relevant!

In your case it seems like 404 is better as it's a page (not an endpoint) and trying to access a non-existing user is supposed to make the application raise an eyebrow.

Note that in the modern age, fancy people would have a special page that says "this user does not exist" specifically for this Users URL.

Gastropod answered 11/4 at 8:9 Comment(0)
S
0
/**
* {@code 422 Unprocessable Entity}.
* @see <a href="https://tools.ietf.org/html/rfc4918#section-11.2">WebDAV</a>
*/
UNPROCESSABLE_ENTITY(422, "Unprocessable Entity")
Surgery answered 12/11, 2020 at 8:5 Comment(3)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer. Kind Regards.Rothschild
I strongly prefer something other than 422 for the OP's described use case, as 422 is typically implemented for malformed body/form/query/<input> parameters and such. As an example, the Python web framework FastAPI uses 422 errors canonically, in my opinion.Peatroy
Yeah no. Unprocessable entity is something else.Gastropod
D
0

Since it's a user-facing page always use 404. It's the only code people know usually.

For the api request, use 400 with the error message "No such user exists" or something along those lines.

Dineen answered 14/12, 2020 at 14:26 Comment(2)
That implies the user will see just the error code and no nice error page. This is not the case though - in any well-made web application, error pages are user-friendly and while they may show the code somewhere, what matters to regular users is the text there.Diffractive
No, don't use 400 for that. Bad request is for when the request was invalid in the first place.Gastropod

© 2022 - 2024 — McMap. All rights reserved.