REST APIs in Depth · Correctness: Errors, Validation, Concurrency and Caching
Validation and Field Errors
Validate at the edge and return every field error in one response.
Validate request syntax (400) and semantics (422) before touching business logic, using schema validation generated from your OpenAPI/JSON Schema or typed models. Return all field errors at once with JSON-pointer-like paths (items[0].quantity) and machine-readable codes (too_small, invalid_format), so UIs can map errors to inputs. Keep business-rule violations (insufficient funds, wrong state) as separate problem types, usually 409/422.
Validation layers
| Layer | What it checks | Typical status |
|---|---|---|
| Transport/parse | Malformed JSON, wrong Content-Type | 400 / 415 |
| Schema | Types, required fields, formats, ranges | 422 |
| Business rules | State transitions, limits, uniqueness | 409 / 422 |
| Authorization | Allowed to act on this resource? | 403 / 404 |
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/problems/validation",
"title": "Your request has invalid fields",
"status": 422,
"errors": [
{"pointer": "/items/0/quantity", "code": "too_small", "detail": "must be at least 1"},
{"pointer": "/shipping/country", "code": "invalid_enum", "detail": "must be an ISO 3166-1 alpha-2 code"}
]
}
Common pitfalls
- Stopping at the first error.
- Only client-side validation.
- Error paths that don't map to request fields.
Key points
- Validate early, return all errors
- Pointers + codes for UIs
- Separate schema vs business-rule errors
Further reading: Understanding JSON Schema
Practice questions
Why include machine-readable error codes alongside messages?
Answer
Clients can localize messages and choose UI behavior (highlight field, suggest fix) without parsing English text.
Is a uniqueness violation a 409 or a 422?
Answer
Either is common; choose one and document it. Many APIs use 409 Conflict for duplicates because the conflict is with existing state.
Open in the app to mark lessons complete, take notes and track your progress.