Search code examples
resthttp-status-code-404semantics

In rest, semantically how to differentiate between 404 returned by a invalid url, vs a 404 returned by a good url pointing to non existen resource?


So I'm actually not a fan of RESTful APIs, yet where I'm hired, they're still used a lot.

So I've come up with a hypothetical case that displays my confusion:

Imagine you have an endpoint GET v1/users/{id}.

Now imagine that there's only one user at the moment, with id 1.

How do I differentiate between the 404 returned by

GET /v1/users/0

and the one returned by

GET /v1/usres/1? (typo on purpose)


Solution

  • How do I differentiate between the 404 returned by....

    Response body, see HTTP Semantics

    Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

    GET /v1/users/0
    
    404 Not Found
    Content-Type: text/plain
    
    There is currently no user 0 in the database
    
    GET /v1/usres/1
    
    404 Not Found
    Content-Type: text/plain
    
    usres? What are you talking about?
    
    Did you mean? 
     * /v1/users/1
     * /v1/ursae/1 
    

    From the perspective of a general purpose component -- ex: a browser, or a cache -- there's absolutely no difference between these two cases.

    But for the client (the human being looking at the web page, or the machine component that is aware of the semantics of your resources), it is reasonable to want to communicate the differences to them.

    For a human, that means returning text that explains the problem into the body of the response (for instance, within an html page).

    For a machine, that means putting in the cues that have been defined by your schema so that machines can distinguish the two cases.