typescriptadvanced
OpenAPI Request Validator
Validates incoming request body against a JSON schema derived from an OpenAPI spec.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Request, Response, NextFunction } from 'express';
interface SchemaProperty {
type: string;
required?: boolean;
minLength?: number;
pattern?: string;
}
interface Schema {
[key: string]: SchemaProperty;
}
function validate(data: Record<string, unknown>, schema: Schema): string[] {
const errors: string[] = [];
for (const [field, rules] of Object.entries(schema)) {
const value = data[field];
if (rules.required && (value === undefined || value === null)) {
errors.push(`${field} is required`);
continue;
}
if (value !== undefined && typeof value !== rules.type) {
errors.push(`${field} must be of type ${rules.type}`);
}
if (rules.minLength && typeof value === 'string' && value.length < rules.minLength) {
errors.push(`${field} must be at least ${rules.minLength} characters`);
}
}
return errors;
}
export function validateBody(schema: Schema) {
return (req: Request, res: Response, next: NextFunction) => {
const errors = validate(req.body, schema);
if (errors.length > 0) {
return res.status(422).json({ errors });
}
next();
};
}Use Cases
- API input validation
- Contract-first development
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Request Validation Schema Builder
Build a lightweight request validation layer with type inference for API endpoints.
Best for: API request body validation
#nodejs#validation
typescriptintermediate
Schema Validation with Zod-like Patterns
Build a minimal schema validation library inspired by Zod using TypeScript type inference.
Best for: API request validation
#nodejs#validation
typescriptintermediate
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Best for: CRUD API endpoints
#api#route-handler
pythonintermediate
Pandera DataFrame Schema Validation
Use Pandera to validate DataFrame schemas with type checks, value constraints, and custom checks.
Best for: pipeline input validation
#pandera#validation