HTTP status code for bad data

Viewed 25307

What HTTP status code should I return when a client posts bad data (e.g. a string when integer was expected)?

I've been using 400 Bad Request, but as I read over the HTTP docs that seems more applicable to HTTP protocol errors.

I'd like to use a status code so that Flash and AJAX clients can distinguish between success, bad data, and server error without having to parse a response.

3 Answers

In case of bad syntax use "400 Bad Request"

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

In case of bad data (and correct syntax) use "422 Unprocessable Entity"

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

See https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

See also https://softwareengineering.stackexchange.com/a/342896/158699 answer, with correct both 400 and 422 code.

Related