Decorators
This section covers Inversify HTTP OpenAPI decorators used to provide OpenAPI metadata to your controllers and operations.
Operation Metadata
These decorators provide metadata for individual API operations (methods).
OasDescription
Adds a description to an API operation, providing detailed information about what the operation does.
OasDescription(content: string): MethodDecorator
Parameters
- content (string): A detailed description of the operation.
Example: adding a description to an operation
@Controller('/messages')
export class DescriptionController {
@OasDescription('Retrieves a welcome message')
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
};
}
}
OasSummary
Adds a brief summary to an API operation, providing a short description of what the operation does.
OasSummary(summary: string): ClassDecorator & MethodDecorator
Parameters
- summary (string): A brief summary of the operation or controller.
Notes
- Scope: Can be applied to both controller classes and individual methods.
Example: adding a summary to an operation
@Controller('/messages')
export class SummaryController {
@OasSummary('Get welcome message')
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
};
}
}
OasOperationId
Sets a unique identifier for the API operation, useful for code generation and tooling.
OasOperationId(content: string): MethodDecorator
Parameters
- content (string): A unique identifier for the operation.
Example: setting an operation ID
@Controller('/messages')
export class OperationIdController {
@OasOperationId('getWelcomeMessage')
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
};
}
}
OasDeprecated
Marks an API operation as deprecated, indicating it will be removed in future versions.
OasDeprecated(): MethodDecorator
Example: marking an operation as deprecated
@Controller('/messages')
export class DeprecatedController {
@OasDeprecated()
@Get()
public async getOldMessage(): Promise<MessageResult> {
return {
message: 'This endpoint is deprecated!',
};
}
}
OasTag
Adds tags to an API operation for grouping and organization in documentation.
OasTag(content: string): MethodDecorator
Parameters
- content (string): The tag name to associate with the operation.
Notes
- Multiple tags: You can apply multiple
@OasTagdecorators to the same operation.
Example: adding tags to an operation
@Controller('/messages')
export class TagController {
@OasTag('messages')
@OasTag('greetings')
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
};
}
}
OasExternalDocs
Links to external documentation for an API operation.
OasExternalDocs(content: OpenApi3Dot1ExternalDocumentationObject): MethodDecorator
Parameters
- content (OpenApi3Dot1ExternalDocumentationObject): External documentation object containing description and URL.
Example: linking to external documentation
@Controller('/messages')
export class ExternalDocsController {
@OasExternalDocs({
description: 'Find more info here',
url: 'https://example.com/docs',
})
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
};
}
}
Request and Response Documentation
These decorators document the request and response structures of your API operations.
OasRequestBody
Documents the request body structure and content types for an API operation.
OasRequestBody(
requestBody:
| OpenApi3Dot1RequestBodyObject
| OpenApi3Dot1ReferenceObject
| BuildOpenApiBlockFunction<
OpenApi3Dot1RequestBodyObject | OpenApi3Dot1ReferenceObject
>,
): MethodDecorator
Parameters
- requestBody: Request body specification or a function that builds it using schema references. See Schema Reference Functions for more information about using the
BuildOpenApiBlockFunction.
Example: documenting a request body
@Controller('/messages')
export class BodyController {
@OasRequestBody({
content: {
'application/json': {
schema: {
properties: {
message: { type: 'string' },
},
required: ['message'],
type: 'object',
},
},
},
})
@Post()
public async createMessage(@Body() body: BodyPayload): Promise<BodyResult> {
return {
message: body.message,
};
}
}
OasResponse
Documents possible response structures and status codes for an API operation.
OasResponse(
code: HttpStatusCode,
response:
| OpenApi3Dot1ResponseObject
| BuildOpenApiBlockFunction<OpenApi3Dot1ResponseObject>,
): MethodDecorator
Parameters
- code (HttpStatusCode): The HTTP status code for this response.
- response: Response specification or a function that builds it using schema references. See Schema Reference Functions for more information about using the
BuildOpenApiBlockFunction.
Notes
- Multiple responses: You can apply multiple
@OasResponsedecorators to document different status codes.
Example: documenting multiple response types
@Controller('/messages')
export class ResponseController {
@OasResponse(HttpStatusCode.OK, {
content: {
'application/json': {
schema: {
properties: {
message: { type: 'string' },
},
required: ['message'],
type: 'object',
},
},
},
description: 'Successful response',
})
@OasResponse(HttpStatusCode.NOT_FOUND, {
content: {
'application/json': {
schema: {
properties: {
error: { type: 'string' },
},
required: ['error'],
type: 'object',
},
},
},
description: 'Message not found',
})
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
};
}
}
OasParameter
Documents parameters for an API operation (query, path, header, or cookie parameters).
OasParameter(
parameter:
| OpenApi3Dot1ParameterObject
| OpenApi3Dot1ReferenceObject
| BuildOpenApiBlockFunction<
OpenApi3Dot1ParameterObject | OpenApi3Dot1ReferenceObject
>,
): MethodDecorator
Parameters
- parameter: Parameter specification or a function that builds it using schema references. See Schema Reference Functions for more information about using the
BuildOpenApiBlockFunction.
Notes
- Multiple parameters: You can apply multiple
@OasParameterdecorators to document different parameters.
Example: documenting a query parameter
@Controller('/messages')
export class ParameterController {
@OasParameter({
description: 'The ID of the user',
in: 'query',
name: 'userId',
required: true,
schema: {
type: 'string',
},
})
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
userId: '123',
};
}
}
Security and Server Configuration
These decorators configure security requirements and server information.
OasSecurity
Specifies security requirements for an API operation.
OasSecurity(content: OpenApi3Dot1SecurityRequirementObject): MethodDecorator
Parameters
- content (OpenApi3Dot1SecurityRequirementObject): Security requirement specification.
Example: requiring bearer authentication
@Controller('/messages')
export class SecurityController {
@OasSecurity({
bearerAuth: [],
})
@Get()
public async getSecureMessage(): Promise<MessageResult> {
return {
message: 'This is a secure message!',
};
}
}
OasServer
Specifies server information for a controller or specific operation.
OasServer(server: OpenApi3Dot1ServerObject): ClassDecorator & MethodDecorator
Parameters
- server (OpenApi3Dot1ServerObject): Server specification including URL and description.
Notes
- Scope: Can be applied to both controller classes and individual methods.
Example: specifying server information
@OasServer({
description: 'Development server',
url: 'http://localhost:3000',
})
@Controller('/messages')
export class ServerController {
@OasServer({
description: 'Production server for this endpoint',
url: 'https://api.example.com',
})
@Get()
public async getMessage(): Promise<MessageResult> {
return {
message: 'Hello, World!',
};
}
}
Schema Definition
These decorators are used to define and document data models.
OasSchema
Defines OpenAPI schema metadata for a class, making it available for reference in other decorators.
OasSchema(
schema?:
| OpenApi3Dot1SchemaObject
| BuildOpenApiBlockFunction<OpenApi3Dot1SchemaObject>,
options?: OasSchemaDecoratorOptions,
): ClassDecorator
Parameters
- schema (optional): Schema specification or a function that builds it. See Schema Reference Functions for more information about using the
BuildOpenApiBlockFunction. - options (optional): Additional options for schema generation. See OasSchemaDecoratorOptions for available options.
OasSchemaDecoratorOptions
The OasSchemaDecoratorOptions interface provides additional configuration options for the @OasSchema decorator:
interface OasSchemaDecoratorOptions {
customAttributes?: OpenApi3Dot1SchemaObject;
name?: string;
}
Properties:
customAttributes(optional): Custom OpenAPI schema attributes to merge with the generated schema. This allows you to add or override specific schema properties.name(optional): Custom name for the schema reference. If not provided, the class name will be used.
Example: defining a schema class
@OasSchema({
description: 'A user in the system',
title: 'User',
})
export class User {
@OasSchemaProperty({
description: 'The unique identifier of the user',
type: 'string',
})
public id!: string;
@OasSchemaProperty({
description: 'The name of the user',
type: 'string',
})
public name!: string;
@OasSchemaProperty({
description: 'The email address of the user',
format: 'email',
type: 'string',
})
public email!: string;
@OasSchemaOptionalProperty({
description: 'The age of the user',
minimum: 0,
type: 'integer',
})
public age?: number;
@OasSchemaOptionalProperty({
description: 'Whether the user is active',
type: 'boolean',
})
public isActive?: boolean;
}
OasSchemaProperty
Marks a class property as required in the OpenAPI schema.
OasSchemaProperty(
schema?:
| OpenApi3Dot1SchemaObject
| BuildOpenApiBlockFunction<OpenApi3Dot1SchemaObject>,
): PropertyDecorator
Parameters
- schema (optional): Schema specification for the property. See Schema Reference Functions for more information about using the
BuildOpenApiBlockFunction.
OasSchemaOptionalProperty
Marks a class property as optional in the OpenAPI schema.
OasSchemaOptionalProperty(
schema?:
| OpenApi3Dot1SchemaObject
| BuildOpenApiBlockFunction<OpenApi3Dot1SchemaObject>,
): PropertyDecorator
Parameters
- schema (optional): Schema specification for the property. See Schema Reference Functions for more information about using the
BuildOpenApiBlockFunction.
Example: using schemas with controllers
@Controller('/users')
export class UserController {
@OasRequestBody((toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: toSchema(CreateUserRequest),
},
},
description: 'User data to create',
required: true,
}))
@OasResponse(HttpStatusCode.OK, (toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: toSchema(User),
},
},
description: 'The created user',
}))
@Post()
public async createUser(@Body() userData: CreateUserRequest): Promise<User> {
return {
email: userData.email,
id: '123',
name: userData.name,
...(userData.age !== undefined && { age: userData.age }),
};
}
@OasResponse(HttpStatusCode.OK, (toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: {
items: toSchema(User),
type: 'array',
},
},
},
description: 'The created user',
}))
@Get()
public async getUsers(): Promise<User[]> {
return [
{
age: 30,
email: 'john@example.com',
id: '1',
name: 'John Doe',
},
{
email: 'jane@example.com',
id: '2',
name: 'Jane Smith',
},
];
}
}
Comprehensive Example
Here's a comprehensive example showing multiple OpenAPI decorators working together:
@OasServer({
description: 'Development server',
url: 'http://localhost:3000',
})
@Controller('/products')
export class ProductController {
@OasSummary('Get all products')
@OasDescription('Retrieves a list of all products in the inventory')
@OasOperationId('getAllProducts')
@OasTag('products')
@OasTag('inventory')
@OasExternalDocs({
description: 'Find more info about products API',
url: 'https://example.com/docs/products',
})
@OasResponse(HttpStatusCode.OK, (toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: {
items: toSchema(Product),
type: 'array',
},
},
},
description: 'List of products',
}))
@Get()
public async getAllProducts(): Promise<Product[]> {
return [
{
description: 'A great laptop',
id: '1',
name: 'Laptop',
price: 999.99,
},
{
id: '2',
name: 'Mouse',
price: 29.99,
},
];
}
@OasSummary('Get product by ID')
@OasDescription('Retrieves a specific product by its unique identifier')
@OasOperationId('getProductById')
@OasTag('products')
@OasParameter({
description: 'The unique identifier of the product',
in: 'path',
name: 'id',
required: true,
schema: {
type: 'string',
},
})
@OasResponse(HttpStatusCode.OK, (toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: toSchema(Product),
},
},
description: 'Product details',
}))
@OasResponse(HttpStatusCode.NOT_FOUND, (toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: toSchema(ErrorResponse),
},
},
description: 'Product not found',
}))
@Get('/:id')
public async getProductById(
@Params() params: { id: string },
): Promise<Product> {
return {
description: 'A great laptop',
id: params.id,
name: 'Laptop',
price: 999.99,
};
}
@OasSummary('Create a new product')
@OasDescription('Creates a new product in the inventory')
@OasOperationId('createProduct')
@OasTag('products')
@OasTag('inventory')
@OasSecurity({
bearerAuth: [],
})
@OasRequestBody((toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: toSchema(CreateProductRequest),
},
},
description: 'Product data to create',
required: true,
}))
@OasResponse(HttpStatusCode.CREATED, (toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: toSchema(Product),
},
},
description: 'Product created successfully',
}))
@OasResponse(HttpStatusCode.BAD_REQUEST, (toSchema: ToSchemaFunction) => ({
content: {
'application/json': {
schema: toSchema(ErrorResponse),
},
},
description: 'Invalid product data',
}))
@Post()
public async createProduct(
@Body() productData: CreateProductRequest,
): Promise<Product> {
return {
id: '123',
name: productData.name,
price: productData.price,
...(productData.description !== undefined && {
description: productData.description,
}),
};
}
@OasSummary('Get legacy product data')
@OasDescription(
'This endpoint is deprecated and will be removed in a future version',
)
@OasOperationId('getLegacyProduct')
@OasTag('products')
@OasTag('legacy')
@OasDeprecated()
@OasResponse(HttpStatusCode.OK, {
content: {
'application/json': {
schema: {
properties: {
data: { type: 'string' },
},
required: ['data'],
type: 'object',
},
},
},
description: 'Legacy product data',
})
@Get('/legacy')
public async getLegacyProduct(): Promise<{ data: string }> {
return {
data: 'This is legacy data',
};
}
}
Schema Reference Functions
When using decorators that accept a BuildOpenApiBlockFunction, you have access to a toSchema function that allows you to reference schema classes:
@OasRequestBody((toSchema) => ({
content: {
'application/json': {
schema: toSchema(MySchemaClass),
},
},
required: true,
}))
MySchemaClass should be properly decorated with @OasSchema and its properties with @OasSchemaProperty or @OasSchemaOptionalProperty.
This approach provides type safety and automatic schema resolution for your OpenAPI documentation.