HTTP status code for bad data

23,027

Solution 1

This is exactly what 400 is for. Yes, it's used for bad HTTP protocol usage, but it's not exclusively for that purpose.

Solution 2

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.

Solution 3

I'd really be more inclined to trap the bad data back in the browser when the client hits the submit button.

If not, then I'd return 400 because as the standard says:

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

Share:
23,027
Ben K.
Author by

Ben K.

Updated on July 09, 2022

Comments

  • Ben K.
    Ben K. almost 2 years

    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.

  • Kevin Meredith
    Kevin Meredith almost 10 years
    Per the OP's question, what if the client issues an HTTP request with an integer, as expected. However, let's say that that integer represents the id of user. If the server can't find that user, should a 400 be returned as well?
  • DasDave
    DasDave over 9 years
    At 404 would be the best thing in that instance @KevinMeredith
  • weberc2
    weberc2 over 8 years
    You should probably do both. There's no guarantees your API is being used by a browser. :)
  • Bill Dagg
    Bill Dagg over 4 years
    Never trust the UI to make a correct request. You definitely should return 400.