Marty Wallace
Marty Wallace

Reputation: 35734

HTTP Status code for generic failure

I am looking for a correct status code to send for a gneral failure through an api.

The exact scenario is failing to add an product to a shopping cart.

The failure could happen for a large number of reasons, but i would like to return a single http code.

Which would be best?

I have been looking through them and cant see anything that exactly fits the needs here.

Some of the possible failure conditions could be:

Not enough stock to satisfy
Stock limit reached for that particular product
Product no longer available

Upvotes: 15

Views: 15301

Answers (2)

Grant Gryczan
Grant Gryczan

Reputation: 1616

Only recently standardized by RFC 9110 (but still widely used before it was standardized thanks to being part of the WebDAV spec), I recommend error 422 for some use cases:

The 422 (Unprocessable Content) status code indicates that the server understands the content type of the request content (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request content is correct, but it was unable to process the contained instructions. For example, this status code can be sent if an XML request content contains well-formed (i.e., syntactically correct), but semantically erroneous XML instructions.

Upvotes: 1

imel96
imel96

Reputation: 1395

If it's server error then it should be 500. If it's client error, use 400.

It's hard to be more precise than that without seeing the URI and what you do with it. For example, if "Product no longer available" is a result of GET request, then it should be 404 (not found). But if it was a POST request, then it should be 200 or 202.

For the other two, they might not be error. It could be the client has sent the correct request but the stock has been consumed by someone else, in this case server should return 409 (conflict) . If the request was for too much stock from the start, then it should just be 200/202.

If you had to have only one code, just use 400 and 200 (see above).

Upvotes: 18

Related Questions