OpenAPI (Swagger) module for Nest framework enabling automatic API documentation generation from TypeScript decorators
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
The @nestjs/swagger interfaces provide comprehensive TypeScript definitions for the complete OpenAPI 3.0 specification, configuration options, and utility types. These interfaces ensure type safety when working with OpenAPI documents and provide full intellisense support for all OpenAPI constructs.
import { getSchemaPath } from '@nestjs/swagger';
function getSchemaPath(model: string | Function): stringReturns the JSON Schema reference path for a given model class or schema name.
Parameters:
model: Either a class constructor or a string representing the schema nameReturns: JSON Schema reference path in the format #/components/schemas/{ModelName}
Usage:
import { getSchemaPath } from '@nestjs/swagger';
class User {
id: string;
name: string;
}
// Get reference path for a class
const userSchemaPath = getSchemaPath(User);
// Returns: "#/components/schemas/User"
// Get reference path for a string
const customSchemaPath = getSchemaPath('CustomSchema');
// Returns: "#/components/schemas/CustomSchema"
// Use in complex schema definitions
@ApiResponse({
status: 200,
schema: {
type: 'object',
properties: {
user: { $ref: getSchemaPath(User) },
permissions: {
type: 'array',
items: { $ref: getSchemaPath('Permission') }
}
}
}
})
getUserWithPermissions() {}import { refs } from '@nestjs/swagger';
function refs(...models: Function[]): Array<{ $ref: string }>Creates an array of schema references for multiple model classes.
Parameters:
...models: Variable number of class constructorsReturns: Array of reference objects with $ref properties
Usage:
import { refs } from '@nestjs/swagger';
class User {}
class Product {}
class Order {}
// Create multiple schema references
const schemaRefs = refs(User, Product, Order);
// Returns: [
// { $ref: "#/components/schemas/User" },
// { $ref: "#/components/schemas/Product" },
// { $ref: "#/components/schemas/Order" }
// ]
// Use in oneOf/anyOf schemas
@ApiResponse({
status: 200,
schema: {
oneOf: refs(User, Product, Order)
}
})
getEntity() {}interface OpenAPIObject {
openapi: string;
info: InfoObject;
servers?: ServerObject[];
paths: PathsObject;
components?: ComponentsObject;
security?: SecurityRequirementObject[];
tags?: TagObject[];
externalDocs?: ExternalDocumentationObject;
}The root OpenAPI specification object containing all API documentation metadata.
Properties:
openapi: OpenAPI specification version (e.g., "3.0.0")info: Required metadata about the APIservers: Array of server objects representing API base URLspaths: Available paths and operations for the APIcomponents: Reusable components (schemas, responses, parameters, etc.)security: Global security requirementstags: List of tags for operation groupingexternalDocs: External documentation referenceUsage:
const openApiDoc: OpenAPIObject = {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0'
},
paths: {
'/users': {
get: {
summary: 'Get users',
responses: {
'200': {
description: 'Successful response'
}
}
}
}
}
};interface InfoObject {
title: string;
description?: string;
termsOfService?: string;
contact?: ContactObject;
license?: LicenseObject;
version: string;
}Metadata about the API including title, description, version, and legal information.
Usage:
const info: InfoObject = {
title: 'E-Commerce API',
description: 'Comprehensive e-commerce platform REST API',
version: '2.1.0',
termsOfService: 'https://example.com/terms',
contact: {
name: 'API Team',
email: 'api@example.com',
url: 'https://example.com/contact'
},
license: {
name: 'MIT',
url: 'https://opensource.org/licenses/MIT'
}
};interface ContactObject {
name?: string;
url?: string;
email?: string;
}Contact information for the API.
interface LicenseObject {
name: string;
url?: string;
}License information for the API.
interface ServerObject {
url: string;
description?: string;
variables?: Record<string, ServerVariableObject>;
}Represents a server where the API is available.
Usage:
const servers: ServerObject[] = [
{
url: 'https://{tenant}.api.example.com/{version}',
description: 'Production server',
variables: {
tenant: {
default: 'main',
enum: ['main', 'staging'],
description: 'Tenant identifier'
},
version: {
default: 'v1',
enum: ['v1', 'v2'],
description: 'API version'
}
}
}
];interface ServerVariableObject {
enum?: string[] | boolean[] | number[];
default: string | boolean | number;
description?: string;
}Represents a server URL template variable.
interface ComponentsObject {
schemas?: Record<string, SchemaObject | ReferenceObject>;
responses?: Record<string, ResponseObject | ReferenceObject>;
parameters?: Record<string, ParameterObject | ReferenceObject>;
examples?: Record<string, ExampleObject | ReferenceObject>;
requestBodies?: Record<string, RequestBodyObject | ReferenceObject>;
headers?: Record<string, HeaderObject | ReferenceObject>;
securitySchemes?: Record<string, SecuritySchemeObject | ReferenceObject>;
links?: Record<string, LinkObject | ReferenceObject>;
callbacks?: Record<string, CallbackObject | ReferenceObject>;
}Container for reusable components in the OpenAPI specification.
Usage:
const components: ComponentsObject = {
schemas: {
User: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' }
}
}
},
responses: {
NotFound: {
description: 'Resource not found'
}
},
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT'
}
}
};type PathsObject = Record<string, PathItemObject>Contains all available paths and operations for the API.
interface PathItemObject {
$ref?: string;
summary?: string;
description?: string;
get?: OperationObject;
put?: OperationObject;
post?: OperationObject;
delete?: OperationObject;
options?: OperationObject;
head?: OperationObject;
patch?: OperationObject;
trace?: OperationObject;
servers?: ServerObject[];
parameters?: (ParameterObject | ReferenceObject)[];
}Describes operations available on a single path.
interface OperationObject {
tags?: string[];
summary?: string;
description?: string;
externalDocs?: ExternalDocumentationObject;
operationId?: string;
parameters?: (ParameterObject | ReferenceObject)[];
requestBody?: RequestBodyObject | ReferenceObject;
responses: ResponsesObject;
callbacks?: CallbacksObject;
deprecated?: boolean;
security?: SecurityRequirementObject[];
servers?: ServerObject[];
}Describes a single API operation on a path.
Usage:
const operation: OperationObject = {
tags: ['Users'],
summary: 'Create a new user',
description: 'Creates a new user account with the provided information',
operationId: 'createUser',
requestBody: {
required: true,
content: {
'application/json': {
schema: { $ref: '#/components/schemas/CreateUserRequest' }
}
}
},
responses: {
'201': {
description: 'User created successfully',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/User' }
}
}
},
'400': {
description: 'Invalid request data'
}
},
security: [
{ bearerAuth: [] }
]
};interface ParameterObject extends BaseParameterObject {
name: string;
in: ParameterLocation;
}
interface BaseParameterObject {
description?: string;
required?: boolean;
deprecated?: boolean;
allowEmptyValue?: boolean;
style?: ParameterStyle;
explode?: boolean;
allowReserved?: boolean;
schema?: SchemaObject | ReferenceObject;
examples?: Record<string, ExampleObject | ReferenceObject>;
example?: any;
content?: ContentObject;
}
type ParameterLocation = 'query' | 'header' | 'path' | 'cookie';
type ParameterStyle = 'matrix' | 'label' | 'form' | 'simple' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject';Describes a single operation parameter.
Usage:
const parameters: ParameterObject[] = [
{
name: 'id',
in: 'path',
required: true,
description: 'User identifier',
schema: {
type: 'string',
format: 'uuid'
}
},
{
name: 'limit',
in: 'query',
required: false,
description: 'Maximum number of results',
schema: {
type: 'integer',
minimum: 1,
maximum: 100,
default: 10
}
}
];interface RequestBodyObject {
description?: string;
content: ContentObject;
required?: boolean;
}Describes request body content for an operation.
interface ResponseObject {
description: string;
headers?: HeadersObject;
content?: ContentObject;
links?: LinksObject;
}
interface ResponsesObject extends Record<string, ResponseObject | ReferenceObject | undefined> {
default?: ResponseObject | ReferenceObject;
}Describes a single response from an API operation.
type ContentObject = Record<string, MediaTypeObject>
interface MediaTypeObject {
schema?: SchemaObject | ReferenceObject;
examples?: ExamplesObject;
example?: any;
encoding?: EncodingObject;
}Describes the content of a request or response body.
Usage:
const responseContent: ContentObject = {
'application/json': {
schema: {
type: 'object',
properties: {
users: {
type: 'array',
items: { $ref: '#/components/schemas/User' }
},
total: {
type: 'integer'
}
}
},
examples: {
userList: {
summary: 'List of users',
value: {
users: [
{ id: '1', name: 'John Doe' },
{ id: '2', name: 'Jane Smith' }
],
total: 2
}
}
}
}
};interface SchemaObject {
// Type and format
type?: string;
format?: string;
// Validation
minimum?: number;
maximum?: number;
exclusiveMinimum?: boolean;
exclusiveMaximum?: boolean;
multipleOf?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
minProperties?: number;
maxProperties?: number;
required?: string[];
enum?: any[];
// Structure
properties?: Record<string, SchemaObject | ReferenceObject>;
additionalProperties?: SchemaObject | ReferenceObject | boolean;
items?: SchemaObject | ReferenceObject;
// Composition
allOf?: (SchemaObject | ReferenceObject)[];
oneOf?: (SchemaObject | ReferenceObject)[];
anyOf?: (SchemaObject | ReferenceObject)[];
not?: SchemaObject | ReferenceObject;
// Metadata
title?: string;
description?: string;
default?: any;
example?: any;
examples?: any[] | Record<string, any>;
// OpenAPI Extensions
nullable?: boolean;
readOnly?: boolean;
writeOnly?: boolean;
deprecated?: boolean;
discriminator?: DiscriminatorObject;
xml?: XmlObject;
externalDocs?: ExternalDocumentationObject;
'x-enumNames'?: string[];
}JSON Schema definition for data models.
Usage:
const userSchema: SchemaObject = {
type: 'object',
required: ['name', 'email'],
properties: {
id: {
type: 'string',
format: 'uuid',
description: 'Unique user identifier',
readOnly: true
},
name: {
type: 'string',
minLength: 1,
maxLength: 100,
description: 'User full name'
},
email: {
type: 'string',
format: 'email',
description: 'User email address'
},
age: {
type: 'integer',
minimum: 0,
maximum: 120,
description: 'User age'
},
role: {
type: 'string',
enum: ['user', 'admin', 'moderator'],
'x-enumNames': ['User', 'Administrator', 'Moderator']
}
},
example: {
id: '123e4567-e89b-12d3-a456-426614174000',
name: 'John Doe',
email: 'john@example.com',
age: 30,
role: 'user'
}
};interface ReferenceObject {
$ref: string;
}Reference to another schema or component.
interface SecuritySchemeObject {
type: SecuritySchemeType;
description?: string;
name?: string;
in?: string;
scheme?: string;
bearerFormat?: string;
flows?: OAuthFlowsObject;
openIdConnectUrl?: string;
'x-tokenName'?: string;
[extension: `x-${string}`]: any;
}
type SecuritySchemeType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect';Defines a security scheme that can be used by operations.
Usage:
const securitySchemes: Record<string, SecuritySchemeObject> = {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
description: 'JWT authorization header'
},
apiKey: {
type: 'apiKey',
in: 'header',
name: 'X-API-Key',
description: 'API key authentication'
},
oauth2: {
type: 'oauth2',
description: 'OAuth2 authentication',
flows: {
authorizationCode: {
authorizationUrl: 'https://auth.example.com/oauth/authorize',
tokenUrl: 'https://auth.example.com/oauth/token',
scopes: {
'read': 'Read access',
'write': 'Write access',
'admin': 'Administrative access'
}
}
}
}
};interface OAuthFlowsObject {
implicit?: OAuthFlowObject;
password?: OAuthFlowObject;
clientCredentials?: OAuthFlowObject;
authorizationCode?: OAuthFlowObject;
}
interface OAuthFlowObject {
authorizationUrl?: string;
tokenUrl?: string;
refreshUrl?: string;
scopes: ScopesObject;
}
type ScopesObject = Record<string, any>;
type SecurityRequirementObject = Record<string, string[]>;OAuth2 flow configurations and security requirements.
interface SwaggerDocumentOptions {
include?: Function[];
extraModels?: Function[];
ignoreGlobalPrefix?: boolean;
deepScanRoutes?: boolean;
operationIdFactory?: OperationIdFactory;
linkNameFactory?: (controllerKey: string, methodKey: string, fieldKey: string) => string;
autoTagControllers?: boolean;
}
type OperationIdFactory = (controllerKey: string, methodKey: string, version?: string) => string;Options for controlling OpenAPI document generation behavior.
Usage:
const documentOptions: SwaggerDocumentOptions = {
include: [UserModule, ProductModule],
extraModels: [BaseResponse, ErrorResponse],
deepScanRoutes: true,
operationIdFactory: (controllerKey, methodKey, version) =>
`${controllerKey.toLowerCase()}_${methodKey}${version ? `_v${version}` : ''}`,
autoTagControllers: true,
ignoreGlobalPrefix: false
};interface SwaggerCustomOptions {
useGlobalPrefix?: boolean;
ui?: boolean;
raw?: boolean | Array<'json' | 'yaml'>;
swaggerUrl?: string;
jsonDocumentUrl?: string;
yamlDocumentUrl?: string;
patchDocumentOnRequest?: <TRequest = any, TResponse = any>(
req: TRequest,
res: TResponse,
document: OpenAPIObject
) => OpenAPIObject;
explorer?: boolean;
swaggerOptions?: SwaggerUiOptions;
customCss?: string;
customCssUrl?: string | string[];
customJs?: string | string[];
customJsStr?: string | string[];
customfavIcon?: string;
customSiteTitle?: string;
customSwaggerUiPath?: string;
}Options for customizing Swagger UI setup and behavior.
Usage:
const swaggerOptions: SwaggerCustomOptions = {
useGlobalPrefix: true,
explorer: true,
customSiteTitle: 'My API Documentation',
swaggerOptions: {
persistAuthorization: true,
displayRequestDuration: true
},
customCss: '.swagger-ui .topbar { display: none; }',
patchDocumentOnRequest: (req, res, document) => {
// Add user-specific modifications
return document;
}
};interface ExampleObject {
summary?: string;
description?: string;
value?: any;
externalValue?: string;
}Example values for schemas and parameters.
interface TagObject {
name: string;
description?: string;
externalDocs?: ExternalDocumentationObject;
}Tag information for grouping operations.
interface ExternalDocumentationObject {
description?: string;
url: string;
}Reference to external documentation.
interface LinkObject {
operationRef?: string;
operationId?: string;
parameters?: LinkParametersObject;
requestBody?: any | string;
description?: string;
server?: ServerObject;
}
type LinkParametersObject = Record<string, any>;Describes relationships between operations.
type CallbackObject = Record<string, PathItemObject>;
type CallbacksObject = Record<string, CallbackObject | ReferenceObject>;Callback definitions for asynchronous operations.
These comprehensive interfaces provide complete type safety and intellisense support for all OpenAPI 3.0 constructs, ensuring your API documentation is both accurate and maintainable.