Request Validation (Zod/Joi)
Runtime validation of incoming API request bodies, query parameters, and path parameters using schema libraries like Zod or Joi.
Description
Request validation ensures that incoming API data conforms to expected types, formats, and business rules before reaching business logic. Libraries like Zod (TypeScript-first, zero dependencies) and Joi (JavaScript, mature ecosystem) allow developers to define schemas declaratively and validate input at the API boundary. Validation should cover request bodies, query parameters, path parameters, and headers, catching malformed input early and returning clear error messages.
Zod has become the preferred choice in TypeScript projects because it infers static types from schemas, eliminating the need to maintain separate TypeScript interfaces and validation schemas. A Zod schema like z.object({ email: z.string().email(), age: z.number().int().min(18) }) serves as both the runtime validator and the TypeScript type. Joi remains popular in JavaScript projects and offers a rich set of built-in validators and custom validation support.
Validation errors should be returned as structured 400 or 422 responses with field-level error details: which field failed, what rule was violated, and what value was received (unless sensitive). A common pattern is to validate at the controller/handler layer using middleware, stripping unknown fields (Zod's .strict() or .strip()) to prevent mass assignment vulnerabilities. Validation schemas should be co-located with route definitions and exported for use in API documentation generation and client SDK type generation.
Prompt Snippet
Define request schemas using Zod co-located with each route handler: const CreateInvoiceBody = z.object({ customer_id: z.string().uuid(), line_items: z.array(LineItemSchema).min(1).max(100), due_date: z.string().datetime() }).strict(). Apply validation in Express middleware using a validate(schema) wrapper that returns 422 with { errors: [{ field: 'customer_id', message: 'Invalid uuid', code: 'invalid_string' }] } on failure. Use z.infer<typeof CreateInvoiceBody> for handler type safety. Strip unknown fields with .strip() to prevent mass-assignment attacks.Tags
Related Terms
API Error Response Format
A standardized structure for error responses that includes machine-readable error codes, human-readable messages, and field-level details.
REST API Conventions
A set of architectural constraints and naming conventions for designing consistent, predictable HTTP APIs around resources.
OpenAPI / Swagger Specification
A machine-readable YAML/JSON specification format for describing REST API endpoints, request/response schemas, authentication, and examples.