What is the recommended REST API response structure when validation fails for multiple fields in a POST request body?
- A.Return 400 with a single error message describing the first validation failure found
- B.Return 400 Bad Request (or 422 Unprocessable Content) with a structured error body listing all field-level violations: { 'errors': [{ 'field': 'email', 'code': 'INVALID_FORMAT', 'message': 'Invalid email format' }, { 'field': 'age', 'code': 'OUT_OF_RANGE', 'message': 'Age must be between 0 and 150' }] }
- C.Return 200 with a 'validationErrors' field alongside the partial data
- D.Return 500 Internal Server Error to indicate the server could not process the malformed request
Why B is correct
400/422 with detailed field-level errors is the user-friendly standard. Report ALL validation errors in one response (not one at a time) to avoid forcing clients through multiple round-trips to fix issues. 400 Bad Request = syntactically malformed (unparseable JSON); 422 Unprocessable Content = syntactically valid but semantically invalid (valid JSON but business rule violations). Error codes (machine-readable) + messages (human-readable) allow client UIs to highlight specific fields and i18n the messages. RFC 7807 Problem Details standardizes this error format.
Know someone studying for Web App Fundamentals? Send them this one.