Search code examples
apistandardshttp-status-codes

Http status code when data not found in Database


I'm trying to understand which Http Status Code to use in the following use case

  1. The user tries to do a GET on an endpoint with an input ID.
  2. The requested data is not available in the database.

Should the service send back:

  1. 404 - Not Found
    As the data is NOT FOUND in the database
  2. 400 - Bad Request
    As the data in the input request is not valid or present in the db
  3. 200 - OK with null response
  4. 200 - OK with an error message
    In this case we can use a standard error message, with a contract that spans across all the 200 OK responses (like below).
 BaseResponse {
  Errors [{
    Message: "Data Not Found"
  }],
  Response: null
 }

Which is the right (or standard) approach to follow?

Thanks in advance.


Solution

  • Which is the right (or standard) approach to follow?

    If you are following the REST API Architecture, you should follow these guidelines:

    400 The request could not be understood by the server due to incorrect syntax. The client SHOULD NOT repeat the request without modifications.

    It means that you received a bad request data, like an ID in alphanumeric format when you want only numeric IDs. Typically it refers to bad input formats or security checks (like an input array with a maxLength)

    404 The server can not find the requested resource.

    The ID format is valid and you can't find the resource in the data source.


    If you don't follow any standard architecture, you should define how you want to manage these cases and share your thought with the team and customers.
    In many legacy applications, an HTTP status 200 with errors field is very common since very-old clients were not so good to manage errors.