I'm currently returning 401 Unauthorized whenever I encounter a validation failure in my Django/Piston based REST API application. Having had a look at the HTTP Status Code Registry I'm not convinced that this is an appropriate code for a validation failure, what do y'all recommend?
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 405 Method Not Allowed
- 406 Not Acceptable
- 412 Precondition Failed
- 417 Expectation Failed
- 422 Unprocessable Entity
- 424 Failed Dependency
Update: "Validation failure" above means an application level data validation failure, i.e., incorrectly specified datetime, bogus email address etc.
Here it is:
rfc2616#section-10.4.1 - 400 Bad Request
rfc7231#section-6.5.1 - 6.5.1. 400 Bad Request
Refers to malformed (not wellformed) cases!
rfc4918 - 11.2. 422 Unprocessable Entity
Conclusion
Rule of thumb: [_]00 covers the most general case and cases that are not covered by designated code.
422 fits best object validation error (precisely my recommendation:)
As for semantically erroneous - Think of something like "This username already exists" validation.
400 is incorrectly used for object validation
There's a little bit more information about the semantics of these errors in RFC 2616, which documents HTTP 1.1.
Personally, I would probably use
400 Bad Request
, but this is just my personal opinion without any factual support.A duplicate in the database should be a
409 CONFLICT
.I recommend using
422 UNPROCESSABLE ENTITY
for validation errors.I give a longer explanation of 4xx codes here: http://parker0phil.com/2014/10/16/REST_http_4xx_status_codes_syntax_and_sematics/
I would say technically it might not be an HTTP failure, since the resource was (presumably) validly specified, the user was authenticated, and there was no operational failure (however even the spec does include some reserved codes like 402 Payment Required which aren't strictly speaking HTTP-related either, though it might be advisable to have that at the protocol level so that any device can recognize the condition).
If that's actually the case, I would add a status field to the response with application errors, like
<status><code>4</code><message>Date range is invalid</message></status>
From RFC 4918 (and also documented at http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml):
What exactly do you mean by "validation failure"? What are you validating? Are you referring to something like a syntax error (e.g. malformed XML)?
If that's the case, I'd say 400 Bad Request is probably the right thing, but without knowing what it is you're "validating", it's impossible to say.