Prompt
How do I validate API schemas at runtime?
Latest observation
Oct 29, 2026
OpenAI APIWeb search: off
To validate API schemas at runtime, you typically combine schema definitions with request/response validation middleware or library calls. The exact approach depends on your stack, but the pattern is the same:
1) Define the schema
Use a schema format like:
- JSON Schema (language-agnostic, common for APIs)
- OpenAPI/Swagger schemas
- Zod, Yup, Joi (popular in JavaScript/TypeScript)
- Pydantic (Python)
- Marshmallow / Cerberus (Python)
Example in JSON Schema:
{
"type": "object",
"required": ["name", "email"],
"properties": {
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" }
},
"additionalProperties": false
}
2) Validate incoming data at the boundary
Validate:
- request bodies
- query params
- path params
- headers
- webhooks / event payloads
- outgoing responses (recommended too)
This ensures malformed data is caught before your business logic runs.
3) Use a runtime validator
JavaScript/TypeScript with Zod
import { z } from "zod";
const UserSchema = z.object({
name: z.string().min(1),
email: z.string().email()
});
const result = UserSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.issues });
}
const user = result.data; // validated data
JavaScript with Ajv (JSON Schema)
import Ajv from "ajv";
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(schema);
if (!validate(req.body)) {
return res.status(400).json({ errors: validate.errors });
}
Python with Pydantic
from pydantic import BaseModel, EmailStr
class User(BaseModel):
name: str
email: EmailStr
try:
user = User.model_validate(request.json())
except Exception as e:
return {"errors": str(e)}, 400
4) Return structured validation errors
Don’t just say “bad request”; return details like:
- which field failed
- expected type/format
- helpful messages
Example:
{
"error": "Validation failed",
"details": [
{ "path": "email", "message": "Invalid email format" }
]
}
5) Enforce strictness
Decide whether to:
- reject unknown fields (
additionalProperties: false) - coerce types (
"123"→123) or reject them - require defaults
- allow partial updates via separate schemas
6) Validate both requests and responses
Response validation helps catch bugs before clients do, especially in large systems.
7) Consider performance
If you validate frequently:
- compile schemas once and reuse them
- avoid re-parsing schema definitions per request
- only validate at API boundaries, not throughout the app
8) Integrate with your framework
Examples:
- Express / Fastify / NestJS
- Django / FastAPI / Flask
- Go with struct tags + validators
- Java/Kotlin with Bean Validation
- Rust with serde + schema validation libs
If you tell me your language/framework, I can give you a concrete runtime validation example.