This document describes NestJS's integration with OpenAPI/Swagger for automatic API documentation generation. It covers the @nestjs/swagger package, document configuration, decorator-based metadata annotation, and the Swagger UI interface for interactive API exploration. For information about data validation that complements Swagger documentation, see Data Validation and Transformation. For REST API implementation patterns, see Routing and Controllers.
Sources: sample/11-swagger/package.json1-54
The @nestjs/swagger package provides OpenAPI 3.0 specification generation by scanning application metadata through decorators applied to controllers, DTOs, and route handlers. The system automatically generates JSON/YAML documents describing endpoints, request/response schemas, authentication requirements, and parameter specifications. A built-in Swagger UI interface allows developers and API consumers to explore and test endpoints interactively.
Sources: sample/11-swagger/package.json25
Diagram: Swagger Integration Architecture
The SwaggerModule scans application metadata collected through decorators, combining it with configuration from DocumentBuilder to generate an OpenAPI specification. The specification is served as both a JSON/YAML document and an interactive Swagger UI interface.
Sources: sample/11-swagger/package.json21-30
| Package | Version | Purpose |
|---|---|---|
@nestjs/swagger | 11.2.6 | Core OpenAPI/Swagger integration |
class-transformer | 0.5.1 | Object serialization/deserialization |
class-validator | 0.14.3 | DTO validation rules |
@nestjs/common | 11.1.13 | HTTP decorators and utilities |
@nestjs/core | 11.1.13 | Core framework features |
The Swagger module integrates with class-validator decorators to automatically infer schema constraints from validation rules, and with class-transformer to understand type transformations applied to request/response payloads.
Sources: sample/11-swagger/package.json21-30
Diagram: Document Generation Sequence
The setup process begins with DocumentBuilder configuring document metadata (title, version, authentication schemes). SwaggerModule.createDocument() then scans the application, collecting metadata from decorators. Finally, SwaggerModule.setup() mounts the Swagger UI at a specified path.
Sources: sample/11-swagger/package.json1-54
The DocumentBuilder provides a fluent API for configuring OpenAPI document metadata:
| Method | Purpose | Example Output |
|---|---|---|
setTitle(string) | Set API title | "Cats API" |
setDescription(string) | Set API description | "The cats API description" |
setVersion(string) | Set API version | "1.0" |
addTag(string) | Group endpoints by tag | "cats", "users" |
setLicense(name, url) | Specify license | "MIT" |
setContact(name, url, email) | API contact info | Developer details |
setExternalDoc(description, url) | Link external docs | Documentation URL |
| Method | Purpose |
|---|---|
addBearerAuth() | JWT/bearer token authentication |
addBasicAuth() | HTTP basic authentication |
addApiKey() | API key authentication (header/query/cookie) |
addOAuth2() | OAuth2 authentication flows |
addCookieAuth() | Cookie-based authentication |
| Method | Purpose |
|---|---|
addServer(url, description) | Add server URL (dev/staging/prod) |
Sources: sample/11-swagger/package.json1-54
Diagram: Controller Decorator Hierarchy
Swagger decorators are applied at three levels: class decorators group endpoints and define shared security requirements, method decorators document individual endpoints, and parameter decorators (via DTOs) describe request/response structures.
Sources: sample/11-swagger/package.json21-30
| Decorator | Purpose | Application |
|---|---|---|
@ApiTags(...tags) | Group endpoints in Swagger UI | Applied to controller class |
@ApiBearerAuth(name?) | Require bearer token auth | Applied to controller or method |
@ApiBasicAuth(name?) | Require basic auth | Applied to controller or method |
@ApiSecurity(name) | Require custom security scheme | Applied to controller or method |
| Decorator | Purpose | Parameters |
|---|---|---|
@ApiOperation({summary, description}) | Document endpoint purpose | Summary and detailed description |
@ApiResponse({status, description, type}) | Document response codes | Status code, description, response DTO |
@ApiOkResponse({type, description}) | Document 200 OK response | Response DTO and description |
@ApiCreatedResponse({type}) | Document 201 Created | Response DTO |
@ApiBadRequestResponse() | Document 400 error | Error description |
@ApiUnauthorizedResponse() | Document 401 error | Auth error description |
@ApiNotFoundResponse() | Document 404 error | Not found description |
| Decorator | Purpose | Parameters |
|---|---|---|
@ApiBody({type, description}) | Document request body | DTO class, description |
@ApiParam({name, type, description}) | Document path parameter | Param name, type, description |
@ApiQuery({name, type, required}) | Document query parameter | Query name, type, required flag |
@ApiHeader({name, description}) | Document required header | Header name, description |
| Decorator | Purpose |
|---|---|
@ApiExcludeEndpoint() | Hide endpoint from documentation |
@ApiExcludeController() | Hide entire controller |
@ApiHideProperty() | Hide DTO property from schema |
Sources: sample/11-swagger/package.json1-54
Diagram: DTO to OpenAPI Schema Mapping
The Swagger module generates OpenAPI schemas by combining TypeScript type information, class-validator constraints, and explicit @ApiProperty() metadata. Validation decorators like @MinLength() automatically populate schema constraints without duplication.
Sources: sample/11-swagger/package.json26-27
| Option | Type | Purpose |
|---|---|---|
description | string | Human-readable field description |
example | any | Example value for documentation |
type | Type | Explicit type (when inference fails) |
required | boolean | Override required/optional status |
default | any | Default value |
enum | array | Enum values for dropdown |
format | string | String format (date-time, email, etc) |
minimum | number | Minimum numeric value |
maximum | number | Maximum numeric value |
minLength | number | Minimum string length |
maxLength | number | Maximum string length |
pattern | string | Regex pattern |
uniqueItems | boolean | Array contains unique items |
| Option | Type | Purpose |
|---|---|---|
nullable | boolean | Allow null values |
isArray | boolean | Property is an array |
readOnly | boolean | Property only in responses |
writeOnly | boolean | Property only in requests |
deprecated | boolean | Mark property as deprecated |
name | string | Override property name in schema |
discriminator | object | Polymorphic schema discriminator |
oneOf | array | One of multiple types |
anyOf | array | Any of multiple types |
allOf | array | All of multiple types |
Sources: sample/11-swagger/package.json26-27
The @nestjs/swagger package includes a CLI plugin that automatically generates many decorators, reducing boilerplate:
| Feature | Without Plugin | With Plugin |
|---|---|---|
| DTO properties | Manual @ApiProperty() on each field | Automatic inference from TypeScript |
| Required fields | Explicit required: true/false | Inferred from ? optional operator |
| Type information | Explicit type: parameter | Inferred from TypeScript types |
| Enum values | Manual enum: array | Inferred from TypeScript enums |
| Default values | Manual default: value | Inferred from initializers |
| Array types | Manual isArray: true | Inferred from Type[] syntax |
Configuration is added to nest-cli.json:
Additional options control plugin behavior:
| Option | Default | Purpose |
|---|---|---|
dtoFileNameSuffix | ['.dto.ts', '.entity.ts'] | Files to process |
controllerFileNameSuffix | '.controller.ts' | Controller file pattern |
classValidatorShim | true | Import validation constraints |
dtoKeyOfComment | 'description' | JSDoc comment mapping |
introspectComments | false | Extract JSDoc descriptions |
Sources: sample/11-swagger/package.json1-54
Diagram: Typical main.ts Setup Flow
The standard setup pattern creates the NestJS application, configures the OpenAPI document using DocumentBuilder, generates the document by scanning the application, and mounts the Swagger UI at a specified path before starting the HTTP server.
Sources: sample/11-swagger/package.json1-54
The SwaggerModule.setup() method accepts a configuration object for customizing the Swagger UI:
| Option | Type | Purpose |
|---|---|---|
customCss | string | Custom CSS styles |
customJs | string | Custom JavaScript file URL |
customfavIcon | string | Custom favicon URL |
customSiteTitle | string | Browser tab title |
swaggerOptions | object | Swagger UI configuration |
| Option | Default | Purpose |
|---|---|---|
deepLinking | true | Enable deep linking to operations |
displayOperationId | false | Show operation IDs |
defaultModelsExpandDepth | 1 | Default expansion depth for models |
defaultModelExpandDepth | 1 | Default expansion for model properties |
displayRequestDuration | false | Show request duration |
docExpansion | 'list' | Controls default expansion ('list', 'full', 'none') |
filter | false | Enable filtering operations |
showExtensions | false | Show vendor extensions |
showCommonExtensions | false | Show common extensions |
persistAuthorization | false | Persist auth across page refreshes |
tryItOutEnabled | false | Enable "Try it out" by default |
| Option | Type | Purpose |
|---|---|---|
jsonDocumentUrl | string | Custom JSON document URL path |
yamlDocumentUrl | string | Custom YAML document URL path |
explorer | boolean | Enable API explorer (default: false) |
swaggerUrl | string | URL to fetch external spec |
Sources: sample/11-swagger/package.json1-54
Diagram: Validation and Documentation Integration
The class-validator decorators serve dual purposes: they enforce validation at runtime through ValidationPipe and automatically populate OpenAPI schema constraints in the documentation. This eliminates duplication between validation rules and API documentation.
Sources: sample/11-swagger/package.json26-28
When multiple response types exist, use @ApiResponse() with different status codes:
| Status Code | Decorator Shorthand | Purpose |
|---|---|---|
| 200 | @ApiOkResponse() | Success response |
| 201 | @ApiCreatedResponse() | Resource created |
| 204 | @ApiNoContentResponse() | No content returned |
| 400 | @ApiBadRequestResponse() | Validation error |
| 401 | @ApiUnauthorizedResponse() | Authentication required |
| 403 | @ApiForbiddenResponse() | Insufficient permissions |
| 404 | @ApiNotFoundResponse() | Resource not found |
| 500 | @ApiInternalServerErrorResponse() | Server error |
For paginated API responses, create generic wrapper DTOs:
| Pattern | Implementation |
|---|---|
| Page metadata | Separate PaginationMetaDto class |
| Generic wrapper | PaginatedDto<T> with @ApiProperty() decorators |
| Type parameter | Use getSchemaPath() helper for generic types |
File upload endpoints require special handling:
| Decorator | Purpose |
|---|---|
@ApiConsumes('multipart/form-data') | Specify content type |
@ApiBody() with schema | Define file field schema |
format: 'binary' | Mark field as binary file |
Enums are automatically documented when used with @ApiProperty():
| Configuration | Result |
|---|---|
| TypeScript enum type | Dropdown with valid values |
enum: option | Explicit enum values |
enumName: option | Named enum in schemas section |
Sources: sample/11-swagger/package.json21-30
For large applications, multiple Swagger documents can be created:
Diagram: Multiple API Document Configuration
The include option in SwaggerModule.createDocument() filters which modules appear in each document, allowing separate documentation for public APIs, admin APIs, and internal services.
Sources: sample/11-swagger/package.json1-54
The sample/11-swagger directory demonstrates a complete Swagger integration:
| Path Pattern | Purpose |
|---|---|
src/**/*.controller.ts | Controllers with @Api*() decorators |
src/**/*.dto.ts | DTOs with @ApiProperty() decorators |
src/main.ts | Swagger setup in bootstrap |
The sample includes all necessary dependencies for a complete Swagger integration:
| Dependency | Purpose |
|---|---|
@nestjs/swagger | Core Swagger module |
class-validator | DTO validation decorators |
class-transformer | Object transformation |
@nestjs/platform-express | HTTP platform adapter |
| Script | Command | Purpose |
|---|---|---|
start:dev | nest start --watch | Run with hot reload |
build | nest build | Production build |
start:prod | node dist/main | Run production build |
When running the sample, the Swagger UI is typically available at http://localhost:3000/api (or the configured path).
Sources: sample/11-swagger/package.json1-54
| Aspect | Impact | Mitigation |
|---|---|---|
| Metadata scanning | Occurs at startup | One-time cost during bootstrap |
| Reflection overhead | Uses reflect-metadata | Cached after first scan |
| Document size | Grows with endpoints | Filter modules with include option |
| Strategy | Implementation | Benefit |
|---|---|---|
| Disable in production | Conditional setup based on environment | No runtime overhead |
| Pre-generate static JSON | Build-time generation | Serve static file |
| Separate docs server | Deploy UI to different service | Isolate documentation traffic |
The generated OpenAPI document is created once at application startup and cached in memory. The Swagger UI static assets are served efficiently by the underlying HTTP adapter (Express or Fastify).
Sources: sample/11-swagger/package.json1-54
Swagger security schemes integrate with authentication systems documented in Authentication and Authorization:
| Auth Type | Swagger Decorator | NestJS Implementation |
|---|---|---|
| JWT Bearer | @ApiBearerAuth() | JwtAuthGuard |
| API Key | @ApiSecurity('api-key') | Custom guard |
| OAuth2 | @ApiOAuth2() | Passport OAuth strategy |
File upload documentation complements the patterns in File Upload Handling:
| Feature | Swagger Annotation | Upload Implementation |
|---|---|---|
| Single file | @ApiBody() with file schema | @UseInterceptors(FileInterceptor()) |
| Multiple files | Array schema with binary format | @UseInterceptors(FilesInterceptor()) |
| Field mapping | Field-level file properties | @UseInterceptors(FileFieldsInterceptor()) |
Swagger schemas reflect the serialization documented in Serialization and Response Transformation:
| Transformation | Swagger Representation | Implementation |
|---|---|---|
@Exclude() property | Property omitted from schema | ClassSerializerInterceptor |
@Expose() property | Property included in schema | @ApiProperty() on exposed field |
| Custom transform | Schema matches output type | @Transform() decorator |
Sources: sample/11-swagger/package.json1-54
Refresh this wiki