2 min read
13. Validation Errors
When a client sends data that fails validation, your API must tell them exactly what went wrong and where. A consistent, machine-parseable error format lets client applications surface field-level feedback without fragile string matching.
The Standard Shape
Return a 422 Unprocessable Entity status code and structure the response as follows:
{ "error": { "code": 422, "message": "Validation failed.", "details": { "email": ["A valid email address is required."], "password": ["Password must be at least 8 characters.", "Password must contain a number."], "name": ["This field is required."] } } }
How to Read the Response
codemirrors the HTTP status code, making it easy to extract without inspecting the status line.messageis a human-readable summary suitable for logging or displaying as a general error notice.detailsis the actionable part. Each key is the name of the field that failed validation. Each value is an array of error messages for that field — an array rather than a single string, because one field can violate multiple rules simultaneously.
Guidelines
- Use the same field names in error details as in the request and response payloads. If your API accepts
email_address, the error key must also beemail_address. - Write error messages for humans. Avoid internal rule identifiers or database constraint names. A message like
"Email must be unique"is far more useful than"UNIQUE constraint failed: users.email". - Return all validation errors at once. Do not stop at the first failing field. Clients want to display every problem to the user in a single pass, not force them to fix and resubmit one field at a time.
- Be consistent across every endpoint. The same field, violating the same rule, should always produce the same error message regardless of which endpoint received the request.