DEV Community

Discussion on: 404 status code! Really?

Collapse
 
scottshipp profile image
scottshipp

IMO 404 all the way 100% o long as we're talking about REST.

The whole REST architectural style is predicated on the idea that the state of a resource at any given moment is temporary:

The key abstraction of information in REST is a resource . . . A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.

Source: Fielding dissertation 5.2.1.1

The idea of the current resource state is hinted at in the immediately following line of the referenced RFC 7231 section 6.5.4

A 404 status code does not indicate whether this lack of representation is temporary or permanent

In other words: the resource does not exist in this API at this moment. However, it might one day. Who knows. But it is 404 Not Found right now.

Reading just one sentence further in the definition of 404 in RFC 7231, you find out that there's a response code for if the resource was there at one point, and is now permanently no longer there:

the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.

This indicates the shared understanding of the author of the RFC of a resource as the mapping to an entity. The entity changes, it has state, but the mapping does not. The mapping identifies that entity permanently.

So to address the issue raised in the above article:

This definition for 200 status code makes me believe that returning a payload with null is correct because it is what exactly the client requested! The client just sent an ID that does not represent any record, the structure of the URI is fine though. Thus, the client gets a success response, but with a null as a resource.

The main reason I believe this is not an accurate interpretation is that the mapping does not exist. And since the resource is the mapping, 404 is the only logical decision.

Besides that, there's already an implicit understanding that if you receive a response, "the structure of the URI" is fine.

Finally, at the end of the day, I think it logically doesn't make sense to tell API consumers 204 No Content or 200 with a null payload, because you would make them think you do have a resource for that given ID within your API, but you're just storing all null values.

This semantic confusion would create similar issues to hash table data structures in some languages that return null values for keys that aren't in the table. Does the null response mean that the key is in the table and currently has the value null? Or does it mean the key isn't in the table? Same problem, and best to avoid.