Request Validation Pattern
Validate all untrusted input at the API boundary before business logic executes. Return all validation errors at once.
Pattern
// Pseudocode — adapt to your stack's validation library
// 1. Define schema
OrderSchema = {
customer_id: required, string, uuid
items: required, array, min_length: 1
items[].product_id: required, string, uuid
items[].quantity: required, integer, min: 1, max: 999
notes: optional, string, max_length: 500
}
// 2. Validate at route handler entry
function createOrder(request):
validation = validate(request.body, OrderSchema)
if validation.hasErrors:
return 400, {
error: {
code: "VALIDATION_ERROR",
message: "Invalid request",
details: validation.errors // [{ field: "items", message: "Required" }]
}
}
// 3. Pass validated data to service
return orderService.create(validation.data)Stack Examples
- Node.js: Zod, Joi, class-validator
- Python: Pydantic, marshmallow, cerberus
- Go: go-playground/validator, ozzo-validation
- Java: Jakarta Bean Validation (Hibernate Validator)
- Ruby: dry-validation, ActiveModel validations