[Fixed] Best way to response as JSON to frontend when the result of a request is null / not found

Issue

To simplify, say you have a REST API with a frontend that has login form in the frontend and you want to check whether a User exists or not. Front-end HTTP/POST some data to the back-end and back-end queries the database. The result is the user does not exist and you want to return that result to the front-end.

I know there might be tons of ways to return the result, but is there any "standard" or "more correct way" to return "User does not exist" result as JSON? Some posibilities i’m thinking:

  1. Return a JSON as a string with the result?
  2. Return empty object?
  3. Return empty User object with a boolean doesNotExist=false?
  4. Return 404 not found or some http code response?
  5. A mix between 4 and 1?

Solution

The standard way to handle the situation where you don’t find a resource is to return a 404 error status. If, for example, your uri is something like /user/{id} then this is an attempt to access a resource/document of type user with the given id, and in this case, if the user is not found then a 404 would be entirely appropriate. You do not need to specifically return a json response in this case.

However, you should be aware that for security purposes it is considered insecure to validate the existence of a user in this way. If an attacker knows a valid username or id they can try to brute-force their password. A lot of systems return the same error for invalid user identifiers and invalid password — invalid credentials — so that attackers cannot know if they have guessed the username correctly. A 401 error is often considered a useful response when attempting to authenticate a user. If the user does not exist or the given creds are invalid, then a 401 should be returned.

Leave a Reply

(*) Required, Your email will not be published