REST - When to use 400 ("Bad Request")

rgullhaug picture rgullhaug · Jun 1, 2012 · Viewed 40k times · Source

I have a resource like this sales/customers/{customerno}. If a client sends a PUT request to this resource I would return 400 - Bad request if the xml in the entity body is not valid xml. But what if the xml is valid, but the content of the xml is not valid. Say for instance that the client is trying to update the customers PostCode and is providing a PostCode which is not valid. Is it correct to return 400 - Bad request in this case, or is it another http code I should have used?

Answer

jmort253 picture jmort253 · Jun 1, 2012

From Wikipedia's List of HTTP Status Codes:

400 Bad Request: The request cannot be fulfilled due to bad syntax.

In this case, your client sent you an XML payload that had an invalid zip code, which is a form of invalid syntax; therefore, sending a 400 Bad Request is an appropriate error code to return in this situation.

In addition, Wikipedia cites RFC-4918 as a resource on this topic. From this document, you'll find the following information:

Servers MAY reject questionable requests (even though they consist of well-formed XML), for instance, with a 400 (Bad Request) status code and an optional response body explaining the problem.

Since your request is well-formed (the XML isn't bad, it just contains semantically incorrect information) you may reject the content with status code 400. The word *may* suggests that there are other options.

While you might be tempted to use status code 422, this would not be correct in this situation, since the invalid zip code does not meet the criteria to be a semantic error. Read below...

From Wikipedia:

422 Unprocessable Entity (WebDAV; RFC 4918): The request was well-formed but was unable to be followed due to semantic errors.

In addition, here are some definitions to assist in the interpretation of status code 422:

  • Syntax errors occur during the parsing of input code, and are caused by grammatically incorrect statements. Typical errors might be an illegal character in the input, a missing operator, two operators in a row, two statements on the same line with no intervening semicolon, unbalanced parentheses, a misplaced reserved word, etc.

  • Semantic errors occur during the execution of the code, after it has been parsed as grammatically correct. These have to do not with how statements are constructed, but with what they mean. Such things as incorrect variable types or sizes, nonexistent variables, subscripts out of range, and the like, are semantic errors.

Your invalid zip code is neither a syntax error nor a semantic error; thus, it's reasonable to rule out status code 422 as an option.

To answer your question, status code 400 is appropriate; however, you may have other options as well.