Is HTTP status 422 appropriate for records that fail uniqueness validation? Is HTTP status 422 appropriate for records that fail uniqueness validation? ruby-on-rails ruby-on-rails

Is HTTP status 422 appropriate for records that fail uniqueness validation?


NB: tried to do a detailed answer below poke's one, but it doesn't seem to be possible, so I will answer here.

I think using 422 for validation errors is fine.

  1. The Webdav RFC doesn't say 422 means "semantic errors", it says the server was "unable to process the contained instructions" (see https://www.rfc-editor.org/rfc/rfc4918#section-11.2). "Semantic errors" are just quoted as an example use case.

  2. 500 is reserved for "an unexpected condition which prevented it from fulfilling the request" (https://www.rfc-editor.org/rfc/rfc2616#section-10.5.1).

500 is usually reserved for real errors, e.g. things that are not handled at all in your code, like crashes. Validation errors are handled, they are not "unexpected", and the client has to change the request so it can be processed (or not). In that sense, the client made the error (for instance submitting a malformed email address will throw a validation error but obviously it's not a server error, right?).

Most APIs I've seen use 400 or 422 for such cases. Maybe there's not one true answer to this, but saying that 500 is the obvious way to go seemed wrong to me.

Hope this helps.


I agree with jbbarth that it's not as simple as 422 vs 500.

422 is good for validation errors, but you don't want to be catching the db errors also.

This is the pattern I use:

if @record.invalid?  # failure of validations => status 422elsif @record.save  # status 200else  # failure when saving => status 500end


While returning a 422 is fine, I'd say failing uniqueness validations should return a 409 Conflict.