Benubird
Benubird

Reputation: 19487

Is it appropriate to use HTTP status codes for non-HTTP errors?

I know someone who is writing an API, and wants to use HTTP status codes to report the outcome of queries. e.g. if the user calls example.com/api/product_info?product_id=X, and the product doesn't exist, it would return HTTP status 400: Bad Request. I think that, since this is a valid call (i.e. the actual HTTP request is not malformed), it should return a 200 code response, and just have the body of the response something like {status: 'error'; message: 'No such product'}.

So my question is,

1) Is it appropriate to use HTTP status codes to convey non-HTTP program state, as in the example above?

2) Is there some standard, or at least widely used, specification describing when HTTP status codes are appropriate for use?

Upvotes: 3

Views: 1638

Answers (1)

Mike Stowe
Mike Stowe

Reputation: 473

I was actually just talking about this the other day - http://blogs.mulesoft.org/api-best-practices-response-handling/

Your status code should reflect the response of the API, as 200 is "OK" and should be used for data that is successfully returned. However, 201 should be used for created items.

As mentioned already, in the event where the user tries a call but it fails (ie: users/?id=5) the server could return back a 400 to inform the user that it was a Bad Request, or a 404 if the resource doesn't exist.

It also depends on the action - if they are searching for a user and there are no responses, I wouldn't return an error, just a 200 with no results found. However, if they are trying to do a PUT or PATCH on a user that doesn't exist I would tell them with an error- as chances are there's a problem within their application somewhere.

In the link posted above you'll find more status codes, but one of the biggest advantages to using status codes is that it informs the client just though the header what actually happened with the server. This allows them to do a relatively quick (and low memory) check instead of having to deserialize the body and loop through an array looking for an errors key.

Essentially, you're giving them the tools to quickly and easily understand what is happening- something that I think every (sane) developer appreciates.

Hope this helps! - Mike

Upvotes: 2

Related Questions