43

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.

Ben K.
  • 1,779
  • 5
  • 18
  • 21
  • Possible duplicate of [Right HTTP status code to wrong input](https://stackoverflow.com/questions/7939137/right-http-status-code-to-wrong-input) – Gabriel Caruso Feb 17 '19 at 01:07

3 Answers3

54

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

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    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? – Kevin Meredith Jul 11 '14 at 17:31
  • 10
    At 404 would be the best thing in that instance @KevinMeredith – DasDave Aug 20 '14 at 11:05
  • @KevinMeredith The appropriate HTTP status code to return depends on the context of the request. For a REST API call where the client expects an empty object when no data is found, returning a 200 OK status code would be appropriate. For a user navigating to a page expecting a URL parameter, returning a 404 Not Found status code and displaying a custom 404 page would be appropriate. – Luca Fagioli Mar 31 '23 at 18:13
10

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.

Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197
7

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.

Rob Wells
  • 36,220
  • 13
  • 81
  • 146