Home > Software design >  What should be the API response for a resource not found
What should be the API response for a resource not found

Time:09-30

given a phone number list where each number starts with 999, and specific customer details are associated with each phone number. 1234567890123 has no customer information associated with it.

So, if a request has the number 1234567890123, should the response be 400 bad request or a 404 not found?

The number 1234567890123 is of proper phone number format, but the additional requirement of the suffix number 999 confuses me as to whether it should be 400 or 404.

CodePudding user response:

404 is specifically for "Not Found". It is not exclusive to "page not found", it is "thing" (i.e. resource) not found.

Use 404 for a validly formatted phone number that is not found.

Use 400 for an invalidly formatted phone number (for example, "123abd" is a 400).

CodePudding user response:

If the input is malformed in such a way that it couldn't possibly match a record (or your system would simply "refuse" to process it), it should be 400 bad request.

If your system would process the query (even without the 999) and it could match a record, then it should be 404.

In my opinion, it would be misleading to say that the resource was found if you know "in advance" that it couldn't possibly exist because the query was "nonsense." As a user, I would assume that 404 meant that it might have existed but didn't; if the system knows that it's not even a sensible request, it should just tell the user that.

Keep in mind that you can include a payload with additional error details; you could indicate to the user in the error message that that's an invalid format.

  • Related