API
OpenApiValidationPipe
Validates incoming request bodies, headers, path parameters, and query parameters against the schemas defined in your OpenAPI specification. The pipe uses Ajv for JSON Schema validation and supports format validation via ajv-formats.
constructor(
openApiObject: OpenApi3Dot1Object,
)
Parameters
- openApiObject (
OpenApi3Dot1ObjectorOpenApi3Dot2Object): The populated OpenAPI document. UseSwaggerUiProvider.openApiObjectto get a fully populated spec after callingprovide(container).
Schema resolution
The pipe constructs a JSON pointer to locate the schema for each request:
<spec-id>#/paths/<path>/<method>/requestBody/content/<content-type>/schema
The path and method are resolved from the BodyValidationInputParam provided by @ValidatedBody(). The content type is resolved using the following strategy:
- If the request has a
Content-Typeheader (extracted by@ValidatedBody()), use its base MIME type. - If the operation declares exactly one content type, use it as the fallback.
- Otherwise, throw an error — the content type is ambiguous.
Lazy initialization
The Ajv instance is created on the first call to execute(). This avoids compilation overhead during application bootstrap and ensures the OpenAPI spec is fully populated before schema compilation.
Example: register an OpenApiValidationPipe globally
import { Controller, Post } from '@inversifyjs/http-core';
import { OasRequestBody, SwaggerUiProvider } from '@inversifyjs/http-open-api';
import { type OpenApi3Dot1Object } from '@inversifyjs/open-api-types/v3Dot1';
import { ValidatedBody } from '@inversifyjs/open-api-validation';
import { OpenApiValidationPipe } from '@inversifyjs/open-api-validation/v3Dot1';
import { Container } from 'inversify';
const container: Container = new Container();
const openApiObject: OpenApi3Dot1Object = {
info: { title: 'My API', version: '1.0.0' },
openapi: '3.1.1',
};
const swaggerProvider: SwaggerUiProvider = new SwaggerUiProvider({
api: {
openApiObject,
path: '/docs',
},
});
interface Message {
content: string;
}
@Controller('/messages')
export class MessageController {
@OasRequestBody({
content: {
'application/json': {
schema: {
additionalProperties: false,
properties: {
content: { maxLength: 200, type: 'string' },
},
required: ['content'],
type: 'object',
},
},
},
})
@Post('/')
public createMessage(@ValidatedBody() message: Message): string {
return `Message: ${message.content}`;
}
}
container.bind(MessageController).toSelf().inSingletonScope();
swaggerProvider.provide(container);
// Create the validation pipe from the populated OpenAPI spec
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const pipe: OpenApiValidationPipe = new OpenApiValidationPipe(
swaggerProvider.openApiObject,
);
ValidatedBody
A custom parameter decorator that extracts the request body along with HTTP method, URL, and Content-Type, and marks the parameter for OpenAPI schema validation.
ValidatedBody(): ParameterDecorator
Apply @ValidatedBody() to any controller method parameter you want to validate against the OpenAPI spec:
@Post('/')
public createUser(@ValidatedBody() user: User): string {
return `Created user: ${user.name}`;
}
@ValidatedBody() is built with createCustomParameterDecorator from @inversifyjs/http-core. It stores a boolean validation marker on the parameter index and provides a handler that extracts the body, HTTP method, URL, and Content-Type from the request at runtime. The OpenApiValidationPipe checks for this marker and uses the extracted request context to validate the body against the OpenAPI schema.
Example: validate request body with OpenAPI schema
import { Controller, Post } from '@inversifyjs/http-core';
import { OasRequestBody } from '@inversifyjs/http-open-api';
import { ValidatedBody } from '@inversifyjs/open-api-validation';
interface Product {
name: string;
price: number;
}
@Controller('/products')
export class ProductController {
@OasRequestBody({
content: {
'application/json': {
schema: {
additionalProperties: false,
properties: {
name: { minLength: 1, type: 'string' },
price: { minimum: 0, type: 'number' },
},
required: ['name', 'price'],
type: 'object',
},
},
},
})
@Post('/')
public createProduct(@ValidatedBody() product: Product): string {
return `Created product: ${product.name}`;
}
}
ValidatedHeaders
A custom parameter decorator that extracts request headers along with the HTTP method and URL, and marks the parameter for OpenAPI header validation.
ValidatedHeaders(): ParameterDecorator
Apply @ValidatedHeaders() to any controller method parameter you want to validate against OpenAPI header parameters defined with @OasParameter():
@Get('/')
public getResources(@ValidatedHeaders() _headers: Record<string, unknown>): string {
return 'ok';
}
@ValidatedHeaders() is built with createCustomParameterDecorator from @inversifyjs/http-core. It stores a boolean validation marker on the parameter index and provides a handler that extracts all request headers, the HTTP method, and URL at runtime. The OpenApiValidationPipe checks for this marker and validates each header individually against its OpenAPI schema, coercing string values to the expected type when needed.
Example: validate request headers with OpenAPI schema
import { Controller, Get } from '@inversifyjs/http-core';
import { OasParameter } from '@inversifyjs/http-open-api';
import { ValidatedHeaders } from '@inversifyjs/open-api-validation';
interface ResourceHeaders {
'x-page-size'?: number;
'x-request-id': string;
}
@Controller('/resources')
export class ResourceController {
@OasParameter({
in: 'header',
name: 'x-request-id',
required: true,
schema: { type: 'string' },
})
@OasParameter({
in: 'header',
name: 'x-page-size',
required: false,
schema: { minimum: 1, type: 'integer' },
})
@Get('/')
public getResources(@ValidatedHeaders() headers: ResourceHeaders): string {
return `Request ID: ${headers['x-request-id']}`;
}
}
Error Handling
When validation fails, the pipe throws an InversifyValidationError with a detailed message containing:
- The JSON Schema path where validation failed
- The instance path in the request body or header
- The validation error message from Ajv
For example, a body validation failure:
[schema: #/properties/email/format, instance: /email]: "must match format \"email\""
A header validation failure:
[schema: #/components/parameters/x-page-size/schema, instance: /x-page-size]: "must be integer"
Use InversifyValidationErrorFilter (from @inversifyjs/http-validation) or a custom @CatchError(InversifyValidationError) filter to convert these errors into HTTP 400 responses.
ValidatedParams
A custom parameter decorator that extracts URL path parameters along with the HTTP method and URL, and marks the parameter for OpenAPI path parameter validation.
ValidatedParams(): ParameterDecorator
Apply @ValidatedParams() to any controller method parameter you want to validate against OpenAPI path parameters defined with @OasParameter({ in: 'path', ... }):
@Get('/:userId')
public getUser(@ValidatedParams() params: Record<string, unknown>): string {
return `User ID: ${String(params['userId'])}`;
}
@ValidatedParams() is built with createCustomParameterDecorator from @inversifyjs/http-core. It stores a boolean validation marker on the parameter index and provides a handler that extracts all URL path parameters, the HTTP method, and URL at runtime. The OpenApiValidationPipe checks for this marker and validates each path parameter individually against its OpenAPI schema, coercing string values to the expected type when needed.
Example: validate URL path parameters with OpenAPI schema
import { Controller, Get } from '@inversifyjs/http-core';
import { OasParameter } from '@inversifyjs/http-open-api';
import { ValidatedParams } from '@inversifyjs/open-api-validation';
interface UserParams {
userId: string;
}
@Controller('/users')
export class UserController {
@OasParameter({
in: 'path',
name: 'userId',
required: true,
schema: { format: 'uuid', type: 'string' },
})
@Get('/:userId')
public getUser(@ValidatedParams() params: UserParams): string {
return `User ID: ${params.userId}`;
}
}
ValidatedQuery
A custom parameter decorator that extracts URL query parameters along with the HTTP method and URL, and marks the parameter for OpenAPI query parameter validation.
ValidatedQuery(): ParameterDecorator
Apply @ValidatedQuery() to any controller method parameter you want to validate against OpenAPI query parameters defined with @OasParameter({ in: 'query', ... }):
@Get('/')
public getProducts(@ValidatedQuery() query: Record<string, unknown>): string {
return `Search: ${String(query['search'])}`;
}
@ValidatedQuery() is built with createCustomParameterDecorator from @inversifyjs/http-core. It stores a boolean validation marker on the parameter index and provides a handler that extracts all query parameters as an object, the HTTP method, and URL at runtime. The OpenApiValidationPipe checks for this marker and validates each query parameter individually against its OpenAPI schema. Because query parameters arrive as strings over HTTP, the pipe uses coerceTypes: true on the Ajv instance and additionally pre-coerces string values to the expected type (boolean, number, null) before validation.
Example: validate query parameters with OpenAPI schema
import { Controller, Get } from '@inversifyjs/http-core';
import { OasParameter } from '@inversifyjs/http-open-api';
import { ValidatedQuery } from '@inversifyjs/open-api-validation';
interface ProductQuery {
limit?: number;
search?: string;
}
@Controller('/products')
export class ProductController {
@OasParameter({
in: 'query',
name: 'search',
required: false,
schema: { type: 'string' },
})
@OasParameter({
in: 'query',
name: 'limit',
required: false,
schema: { minimum: 1, type: 'integer' },
})
@Get('/')
public getProducts(@ValidatedQuery() query: ProductQuery): string {
return `Search: ${query.search ?? ''}`;
}
}