Lesson 5 of 9 · 20m
Validation and Error Contracts
Validate at the trust boundary, separate input errors from domain conflicts, and return errors clients can safely automate against.
Validation is not about being picky. It is the point where untrusted bytes become typed domain input. If malformed data crosses that boundary, every layer below inherits the risk: broken queries, inconsistent state, and stack traces that leak your internals.
Validate shape first, meaning second
Shape validation asks whether the request is structurally usable: types, required fields, lengths, formats. Domain validation asks whether the request is allowed in the current state.
$data = $request->validate([
'email' => ['required', 'email:rfc', 'max:320'],
'quantity' => ['required', 'integer', 'min:1', 'max:1000'],
'currency' => ['required', 'string', 'size:3', 'in:USD,EUR,GBP'],
]);
if ($order->status !== OrderStatus::Draft) {
throw new ConflictHttpException('Only draft orders can be changed.');
}The first block is 422 material. The second is usually 409: the payload is fine, but the object's current state rejects the transition.
Never trust client-provided ownership fields
If a client sends user_id, tenant_id, or price, assume it is hostile. Derive ownership from the authenticated context and derive price from server-side catalog state. Client input may select which catalog item to buy; it may not decide what it costs.
Error responses are an API surface
Adopt one error format and use it everywhere. RFC 7807 problem details is a solid baseline:
{
"type": "https://api.sudosecurity.org/problems/validation-failed",
"title": "Validation failed", "status": 422,
"detail": "quantity must be between 1 and 1000",
"instance": "/v1/orders/ord_9c8b7a/items",
"errors": [{"field": "quantity", "code": "out_of_range"}]
}Machine-readable code values matter. Humans can parse prose, but clients need stable symbolic errors for localization and automation.
Fail closed without leaking internals
A missing required field is a client error. A database exception is not. Log the exception with a request ID, return a generic 500, and include that ID in the response so support can correlate it:
{"type": "about:blank", "title": "Internal server error", "status": 500,
"requestId": "req_01J8ZJ1G1QYA4T5N4R8M4H6A7V"}Do not include SQL, file paths, class names, or framework traces in production responses. They are reconnaissance material.
Reject unknown fields when mutation is expensive
For PATCH-like endpoints, silently ignoring misspelled fields creates confusing behavior: the client believes quantity changed because it sent quantitiy. In high-integrity APIs, reject unknown keys or at least return warnings. Strictness early is cheaper than compatibility archaeology later.
Field notes
- Validate types before casting; PHP's loose comparisons and numeric-string behavior can surprise you.
- Unicode length is not byte length. Decide which one your limits mean.
- Error codes are contract. Rename them only through versioning or a deprecation process.
- Keep authorization failures distinct from validation failures; attackers use error differences to map the object graph.
Was this lesson helpful?