### setup Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/swagger-module.md Example demonstrating how to use the setup method to serve Swagger UI. ```typescript const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('My API') .setVersion('1.0.0') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('/api/docs', app, document, { useGlobalPrefix: true, swaggerOptions: { persistAuthorization: true } }); await app.listen(3000); ``` -------------------------------- ### Basic Setup Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/swagger-module.md A complete example showing the basic setup of SwaggerModule in a NestJS application. ```typescript import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('My API') .setDescription('My awesome API') .setVersion('1.0') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); console.log('Swagger UI is running at http://localhost:3000/api'); } bootstrap(); ``` -------------------------------- ### Minimal Application Setup Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/configuration.md A minimal configuration example for setting up Swagger in a NestJS application, including DocumentBuilder and SwaggerModule. ```typescript import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('API') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Swagger Module Setup Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Example of setting up the Swagger module for document generation and Swagger UI configuration in a NestJS application. ```typescript const document = SwaggerModule.createDocument(app, config, { include: [UsersModule], extraModels: [ErrorDto], ignoreGlobalPrefix: false, deepScanRoutes: true, autoTagControllers: true }); SwaggerModule.setup('api/docs', app, document, { useGlobalPrefix: true, ui: true, raw: ['json', 'yaml'], swaggerOptions: { persistAuthorization: true, docExpansion: 'list' }, customCss: '...', customSiteTitle: 'My API' }); ``` -------------------------------- ### Environment-Based Configuration Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/configuration.md An example showing how to configure Swagger differently for production and development environments, including conditional setup and different documentation endpoints. ```typescript import { NestFactory, } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule, } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const isProduction = process.env.NODE_ENV === 'production'; if (!isProduction) { const config = new DocumentBuilder() .setTitle('Development API') .setVersion('1.0') .setDescription('Development environment - all endpoints available') .build(); const document = SwaggerModule.createDocument(app, config, { deepScanRoutes: true, }); SwaggerModule.setup('api/docs', app, document, { swaggerOptions: { persistAuthorization: true, docExpansion: 'full', }, }); console.log('Swagger documentation available at http://localhost:3000/api/docs'); } else { // Limited documentation in production const config = new DocumentBuilder() .setTitle('Production API') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api/public-docs', app, document, { ui: false, raw: ['json'], }); } await app.listen(3000); } bootstrap(); ``` -------------------------------- ### PickType Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example demonstrating how to use PickType to create a login DTO with only specific properties. ```typescript export class CreateUserDto { @ApiProperty() email: string; @ApiProperty() password: string; @ApiProperty() name: string; @ApiProperty() phone: string; } // Create a login DTO with only email and password export class LoginDto extends PickType(CreateUserDto, ['email', 'password']) {} // Now contains: // { // email: string; // password: string; // } ``` -------------------------------- ### Install NestJS Swagger Module Source: https://github.com/nestjs/swagger/blob/master/README.md Use this command to install the @nestjs/swagger package. ```bash npm i --save @nestjs/swagger ``` -------------------------------- ### loadPluginMetadata Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/swagger-module.md Example demonstrating how to use the loadPluginMetadata method. ```typescript const metadata = await SwaggerModule.loadPluginMetadata(() => import('./generated-metadata.json') ); ``` -------------------------------- ### SwaggerModule Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Example of using SwaggerModule to create documents and set up Swagger UI. ```typescript import { SwaggerModule } from '@nestjs/swagger'; const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api/docs', app, document); ``` -------------------------------- ### createDocument Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/swagger-module.md Example demonstrating how to use the createDocument method to generate an OpenAPI document. ```typescript const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('My API') .setVersion('1.0.0') .build(); const document = SwaggerModule.createDocument(app, config); ``` -------------------------------- ### SwaggerModule.setup() Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/configuration.md Complete configuration options for `SwaggerModule.setup()`. ```typescript SwaggerModule.setup('api/docs', app, document, { useGlobalPrefix: true, ui: true, raw: ['json'], swaggerOptions: { persistAuthorization: true, docExpansion: 'list' }, customCss: `.swagger-ui .topbar { display: none; }`, customSiteTitle: 'My API Docs', customfavIcon: 'https://example.com/favicon.ico' }); ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/configuration.md A comprehensive example demonstrating various configuration options for Swagger, including API details, servers, tags, authentication methods, and custom options. ```typescript import { NestFactory, } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule, } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const globalPrefix = 'api/v1'; app.setGlobalPrefix(globalPrefix); const config = new DocumentBuilder() .setTitle('My Awesome API') .setDescription('Complete API documentation') .setVersion('1.0.0') .setContact('Support', 'https://support.example.com', 'support@example.com') .setLicense('MIT', 'https://opensource.org/licenses/MIT') .setTermsOfService('https://example.com/terms') .addServer('https://api.example.com', 'Production') .addServer('https://staging.example.com', 'Staging') .addServer('http://localhost:3000', 'Development') .addTag('Users', 'User management operations') .addTag('Products', 'Product catalog operations') .addBearerAuth() .addApiKey({ type: 'apiKey', in: 'header', name: 'X-API-Key' }, 'api_key') .addBasicAuth() .addSecurityRequirements('bearer') .build(); const document = SwaggerModule.createDocument(app, config, { include: [AppModule], ignoreGlobalPrefix: false, deepScanRoutes: true, autoTagControllers: true, operationIdFactory: (controllerKey, methodKey) => `${controllerKey}_${methodKey}`, }); SwaggerModule.setup('docs', app, document, { useGlobalPrefix: true, ui: true, raw: ['json', 'yaml'], swaggerOptions: { persistAuthorization: true, docExpansion: 'list', filter: true, showRequestHeaders: true, displayOperationId: true, displayRequestDuration: true, defaultModelsExpandDepth: 2, defaultModelExpandDepth: 2, deepLinking: true, presets: [ // SwaggerUIBundle.presets.apis, // SwaggerUIStandalonePreset ], }, customCss: ` .swagger-ui .topbar { display: none; } .swagger-ui { color: #3f51b5; } `, customSiteTitle: 'My API Documentation', customfavIcon: 'https://example.com/favicon.ico', patchDocumentOnRequest: async (req, res, document) => { // Add tenant-specific configuration const tenantId = req.headers['x-tenant-id']; if (tenantId) { document.info.title += ` (Tenant: ${tenantId})`; } return document; }, }); await app.listen(3000); console.log(`Swagger documentation available at http://localhost:3000/${globalPrefix}/docs`); } bootstrap(); ``` -------------------------------- ### DocumentBuilder Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Example of using DocumentBuilder to construct the base OpenAPI specification. ```typescript import { DocumentBuilder } from '@nestjs/swagger'; const config = new DocumentBuilder() .setTitle('My API') .setVersion('1.0.0') .addBearerAuth() .build(); ``` -------------------------------- ### PartialType Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example demonstrating how to use PartialType to create an update DTO with optional fields. ```typescript // Original DTO export class CreateUserDto { @ApiProperty() @IsEmail() email: string; @ApiProperty() @MinLength(8) password: string; @ApiProperty() @IsString() name: string; } // Update DTO using PartialType export class UpdateUserDto extends PartialType(CreateUserDto) {} // Now all fields are optional: // { // email?: string; // password?: string; // name?: string; // } ``` -------------------------------- ### Utility Functions Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Examples of using utility functions for schema references and generation. ```typescript import { getSchemaPath, refs, generateSchema } from '@nestjs/swagger'; const userRef = getSchemaPath(UserDto); // '#/components/schemas/UserDto' const refs = refs(UserDto, ProductDto); // Array of references const schema = generateSchema(CreateUserDto); // Generate schema from type ``` -------------------------------- ### setup Method Signature Source: https://github.com/nestjs/swagger/blob/master/_autodocs/swagger-module.md Signature for the setup static method, which configures and serves Swagger UI. ```typescript static setup( path: string, app: INestApplication, documentOrFactory: OpenAPIObject | (() => OpenAPIObject), options?: SwaggerCustomOptions ): void ``` -------------------------------- ### SwaggerModule.loadPluginMetadata Usage Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md Example demonstrating how to use SwaggerModule.loadPluginMetadata in application bootstrap. ```typescript async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('My API') .setVersion('1.0') .build(); // Load plugin-generated metadata const metadata = await SwaggerModule.loadPluginMetadata(() => import('./metadata.json') ); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Basic Setup with Plugin Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md This code snippet demonstrates the basic setup of the Swagger plugin within an AppModule, including creating a document builder, generating the Swagger document, and setting up the Swagger UI endpoint. ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { NestFactory } from '@nestjs/core'; @Module({ imports: [], controllers: [], providers: [] }) export class AppModule {} async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('User API') .setVersion('1.0.0') .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api/docs', app, document); await app.listen(3000); } bootstrap(); ``` ```typescript // users/users.controller.ts import { Controller, Get, Post, Body, Param } from '@nestjs/common'; import { UsersService } from './users.service'; import { CreateUserDto } from './dto/create-user.dto'; @Controller('users') export class UsersController { constructor(private usersService: UsersService) {} @Get() findAll() { return this.usersService.findAll(); } @Post() create(@Body() createUserDto: CreateUserDto) { return this.usersService.create(createUserDto); } @Get(':id') findOne(@Param('id') id: string) { return this.usersService.findOne(id); } } ``` ```typescript // users/dto/create-user.dto.ts import { IsEmail, MinLength, IsOptional } from 'class-validator'; /** * DTO for creating a new user */ export class CreateUserDto { /** * User's email address - must be unique * @example user@example.com */ @IsEmail() email: string; /** * User's password - minimum 8 characters * @minLength 8 */ @MinLength(8) password: string; /** * User's display name * @example John Doe */ name: string; /** * Optional phone number * @example +1234567890 */ @IsOptional() phone?: string; } ``` -------------------------------- ### Type Helpers Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Examples of using type helper functions to create new DTO classes. ```typescript import { PartialType, PickType, OmitType } from '@nestjs/swagger'; export class UpdateUserDto extends PartialType(CreateUserDto) {} export class LoginDto extends PickType(CreateUserDto, ['email', 'password']) {} export class UserResponseDto extends OmitType(UserDto, ['passwordHash']) {} ``` -------------------------------- ### IntersectionType Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example demonstrating how to use IntersectionType to combine DTOs for a complete user object. ```typescript export class AddressDto { @ApiProperty() street: string; @ApiProperty() city: string; @ApiProperty() country: string; } export class ProfileDto { @ApiProperty() bio: string; @ApiProperty() avatar: string; } export class CreateUserDto { @ApiProperty() email: string; @ApiProperty() name: string; } // Combined type with all properties export class CompleteUserDto extends IntersectionType( CreateUserDto, ProfileDto, AddressDto ) {} // Now contains all properties from all three DTOs: // { // email: string; // name: string; // bio: string; // avatar: string; // street: string; // city: string; // country: string; // } ``` -------------------------------- ### TypeScript Plugin Configuration Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/INDEX.md Example configuration for the @nestjs/swagger plugin in nest-cli.json. ```json { "compilerOptions": { "plugins": [{ "name": "@nestjs/swagger/plugin", "options": { "classValidatorShim": true, "introspectComments": true, "autoTagControllers": true } }] } } ``` -------------------------------- ### Complete Usage Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md A comprehensive example demonstrating the usage of DocumentBuilder to create an OpenAPI document for a NestJS application. ```typescript import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('User API') .setDescription('API for managing users') .setVersion('1.0.0') .setContact('Support', 'https://support.example.com', 'support@example.com') .setLicense('MIT', 'https://opensource.org/licenses/MIT') .setTermsOfService('https://example.com/terms') .addServer('https://api.example.com', 'Production') .addServer('http://localhost:3000', 'Development') .addTag('Users', 'User management operations') .addBearerAuth() .addSecurityRequirements('bearer') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api/docs', app, document); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Swagger UI Options Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/configuration.md Example of setting various Swagger UI options like docExpansion, filter, and OAuth2 configuration. ```typescript SwaggerModule.setup('api/docs', app, document, { swaggerOptions: { docExpansion: 'full', filter: true, displayOperationId: true, persistAuthorization: true, tryItOutEnabled: true, defaultModelExpandDepth: 2, initOAuth: { clientId: 'your-client-id', clientSecret: 'your-client-secret', realm: 'your-realm', appName: 'My App', scopes: ['read:api', 'write:api'] } } }); ``` -------------------------------- ### Commit Message Examples Source: https://github.com/nestjs/swagger/blob/master/CONTRIBUTING.md Examples of valid commit messages following the project's conventional commit format, which includes a type, scope, and subject. ```text docs(changelog) update change log to beta.5 fix(@nestjs/core) need to depend on latest rxjs and zone.js The version in our package.json gets copied to the one we publish, and users need the latest of these. ``` -------------------------------- ### OmitType Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example demonstrating how to use OmitType to create a response DTO excluding sensitive fields. ```typescript export class UserDto { @ApiProperty() id: string; @ApiProperty() email: string; @ApiProperty() name: string; @ApiProperty() passwordHash: string; // Should never be in responses } // Response DTO without sensitive fields export class UserResponseDto extends OmitType(UserDto, ['passwordHash']) {} // Now contains: // { // id: string; // email: string; // name: string; // } ``` -------------------------------- ### PickType API Impact Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example showing the API impact of using PickType in controller endpoints. ```typescript @Controller('auth') export class AuthController { @Post('login') @ApiBody({ type: LoginDto }) login(@Body() loginDto: LoginDto) { // Only email and password required return this.authService.login(loginDto.email, loginDto.password); } } ``` -------------------------------- ### Nest CLI JSON Plugin Configuration Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/configuration.md Example of configuring the @nestjs/swagger plugin within the nest-cli.json file, including options like classValidatorShim and introspectComments. ```json { "$schema": "https://json.schemastore.org/nest-cli", "collection": "@nestjs/schematics", "sourceRoot": "src", "compilerOptions": { "deleteOutDir": true, "plugins": [ { "name": "@nestjs/swagger/plugin", "options": { "classValidatorShim": true, "introspectComments": true, "autoTagControllers": true, "dtoFileNameSuffix": [".entity.ts", ".dto.ts"], "controllerFileNameSuffix": ".controller.ts" } } ] } } ``` -------------------------------- ### PartialType API Impact Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example showing the API impact of using PartialType in controller endpoints. ```typescript @Controller('users') export class UsersController { @Post() @ApiBody({ type: CreateUserDto }) create(@Body() createUserDto: CreateUserDto) { // All fields required } @Patch(':id') @ApiBody({ type: UpdateUserDto }) update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) { // All fields optional } } ``` -------------------------------- ### SwaggerModule Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/INDEX.md Static methods for document generation and UI serving. ```typescript const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api/docs', app, document); ``` -------------------------------- ### Advanced Setup with Plugin Metadata Source: https://github.com/nestjs/swagger/blob/master/_autodocs/swagger-module.md Demonstrates how to set up Swagger with plugin metadata, including server definitions, bearer authentication, tags, and loading metadata from a JSON file. ```typescript import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const globalPrefix = 'api'; app.setGlobalPrefix(globalPrefix); const config = new DocumentBuilder() .setTitle('Advanced API') .setDescription('API using TypeScript plugin') .setVersion('2.0') .addServer(`http://localhost:3000/${globalPrefix}`, 'Development') .addBearerAuth() .addTag('Users') .addTag('Products') .build(); // Load metadata generated by the plugin const metadata = await SwaggerModule.loadPluginMetadata(() => import('./metadata.json') ); const document = SwaggerModule.createDocument(app, config, { include: [AppModule], extraModels: [SomeExtraModel] }); SwaggerModule.setup('docs', app, document, { useGlobalPrefix: true, swaggerOptions: { persistAuthorization: true, docExpansion: 'list', tagsSorter: 'alpha' } }); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### DocumentBuilder Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/INDEX.md Fluent API for configuring OpenAPI document metadata. ```typescript const config = new DocumentBuilder() .setTitle('My API') .setVersion('1.0.0') .addBearerAuth() .build(); ``` -------------------------------- ### SwaggerModule.createDocument() Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/configuration.md Configuration for `SwaggerModule.createDocument()`. ```typescript const document = SwaggerModule.createDocument(app, config, { include: [UsersModule, ProductsModule], extraModels: [ErrorDto, PaginationDto], ignoreGlobalPrefix: false, deepScanRoutes: true, autoTagControllers: true, operationIdFactory: (controllerKey, methodKey, version) => { return `${controllerKey}_${methodKey}${version ? `_v${version}` : ''}`; } }); ``` -------------------------------- ### DeepPartialType Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example demonstrating the use of DeepPartialType to create an update DTO where all fields are optional, including nested ones. ```typescript export class AddressDto { @ApiProperty() street: string; @ApiProperty() city: string; } export class UserDto { @ApiProperty() email: string; @ApiProperty() name: string; @ApiProperty({ type: AddressDto }) address: AddressDto; } // Deep partial where address and its properties are optional export class UpdateUserDeepDto extends DeepPartialType(UserDto) {} // Now contains: // { // email?: string; // name?: string; // address?: { // street?: string; // city?: string; // }; // } ``` -------------------------------- ### Basic Endpoint Documentation Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Example demonstrating basic endpoint documentation using NestJS Swagger decorators for a user controller. ```typescript import { Controller, Get, Post, Body, Param } from '@nestjs/common'; import { ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger'; import { UsersService } from './users.service'; import { CreateUserDto } from './dto/create-user.dto'; import { UserDto } from './dto/user.dto'; @Controller('users') export class UsersController { constructor(private usersService: UsersService) {} @Get(':id') @ApiOperation({ summary: 'Get user by ID' }) @ApiParam({ name: 'id', type: String, description: 'User ID' }) @ApiResponse({ status: 200, type: UserDto }) @ApiResponse({ status: 404, description: 'User not found' }) getUser(@Param('id') id: string) { return this.usersService.findOne(id); } @Post() @ApiOperation({ summary: 'Create a new user' }) @ApiBody({ type: CreateUserDto }) @ApiResponse({ status: 201, type: UserDto }) @ApiResponse({ status: 400, description: 'Invalid input' }) createUser(@Body() createUserDto: CreateUserDto) { return this.usersService.create(createUserDto); } } ``` -------------------------------- ### OmitType API Impact Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md An example showing the API impact of using OmitType in controller endpoints. ```typescript @Controller('users') export class UsersController { @Get(':id') @ApiResponse({ type: UserResponseDto }) findOne(@Param('id') id: string) { const user = this.usersService.findOne(id); // Safe to return: passwordHash is excluded from the schema return user; } } ``` -------------------------------- ### ApiBody Decorator Example (Single and Array) Source: https://github.com/nestjs/swagger/blob/master/_autodocs/decorators.md Illustrates the use of the @ApiBody decorator for documenting request bodies, showing examples for a single DTO and an array of DTOs. ```typescript @Post() @ApiBody({ type: CreateUserDto, description: 'User creation data' }) create(@Body() createUserDto: CreateUserDto) { return this.usersService.create(createUserDto); } @Post('bulk') @ApiBody({ type: [CreateUserDto], isArray: true, description: 'Array of users to create' }) createBulk(@Body() users: CreateUserDto[]) { return this.usersService.createBulk(users); } ``` -------------------------------- ### Decorators Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/INDEX.md Method, parameter, class, and property decorators for documenting various aspects of an API. ```typescript @Get(':id') @ApiParam({ name: 'id', type: String }) @ApiResponse({ status: 200, type: UserDto }) findOne(@Param('id') id: string) { return this.usersService.findOne(id); } ``` -------------------------------- ### Combined Usage Examples: Controller Usage Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md Shows how the different DTOs created through type transformations are used in NestJS controller endpoints. ```typescript @Controller('products') export class ProductsController { @Post() @ApiBody({ type: CreateProductDto }) create(@Body() createProductDto: CreateProductDto) { return this.productsService.create(createProductDto); } @Put(':id') @ApiBody({ type: UpdateProductDto }) update(@Param('id') id: string, @Body() updateProductDto: UpdateProductDto) { return this.productsService.update(id, updateProductDto); } @Get() @ApiResponse({ type: [ProductListDto] }) findAll() { return this.productsService.findAll(); } @Post('search') @ApiBody({ type: ProductSearchDto }) search(@Body() searchDto: ProductSearchDto) { return this.productsService.search(searchDto); } } ``` -------------------------------- ### refs Example Usage Source: https://github.com/nestjs/swagger/blob/master/_autodocs/utility-functions.md Demonstrates how to use the refs function to generate multiple references. ```typescript import { refs, getSchemaPath } from '@nestjs/swagger'; const references = refs(UserDto, ProductDto, OrderDto); // Returns: [ // { $ref: '#/components/schemas/UserDto' }, // { $ref: '#/components/schemas/ProductDto' }, // { $ref: '#/components/schemas/OrderDto' } // ] ``` -------------------------------- ### Combined Usage Examples: Multi-step DTO Transformation Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md Demonstrates various DTO transformations using PartialType, OmitType, PickType, and IntersectionType for different API needs. ```typescript // Base DTO export class CreateProductDto { @ApiProperty() name: string; @ApiProperty() description: string; @ApiProperty() price: number; @ApiProperty() sku: string; @ApiProperty() internal_cost: number; } // For updates: all fields optional export class UpdateProductDto extends PartialType(CreateProductDto) {} // For listing: exclude sensitive fields export class ProductListDto extends OmitType(CreateProductDto, ['internal_cost', 'sku']) {} // For search filters: pick only search fields export class ProductSearchDto extends PickType(CreateProductDto, ['name', 'sku']) {} // For bulk operations: combine multiple concerns export class BulkProductUpdateDto extends IntersectionType( ProductSearchDto, PartialType(OmitType(CreateProductDto, ['internal_cost'])) ) {} ``` -------------------------------- ### Utility Functions Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/INDEX.md Helper functions for schema path generation and references. ```typescript const userRef = getSchemaPath(UserDto); // '#/components/schemas/UserDto' const references = refs(UserDto, ProductDto); ``` -------------------------------- ### Usage in nest-cli.json for 'before' export Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md Example of how to configure the plugin's 'before' export in nest-cli.json. ```json { "compilerOptions": { "plugins": [ { "name": "@nestjs/swagger/plugin", "options": { "autoTagControllers": true } } ] } } ``` -------------------------------- ### Type Helpers Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/INDEX.md Functions for creating transformed DTO types. ```typescript export class UpdateUserDto extends PartialType(CreateUserDto) {} export class LoginDto extends PickType(CreateUserDto, ['email', 'password']) {} ``` -------------------------------- ### TypeDoc Comment Annotations Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md This TypeScript code example illustrates how to use TypeDoc comment annotations to provide OpenAPI metadata for DTO properties, such as examples, minimum/maximum values, and deprecation notices. ```typescript export class ProductDto { /** * Product identifier * @example 12345 */ id: number; /** * Product name * @example "Awesome Product" */ name: string; /** * Product price in cents * @minimum 0 * @maximum 1000000 * @example 9999 */ price: number; /** * Product categories * @isArray true */ categories: string[]; /** * Product description * @deprecated Use 'details' field instead */ description?: string; /** * Detailed product information */ details: string; } ``` -------------------------------- ### setDescription Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets the description of the API specification. Returns `this` for method chaining. ```typescript const config = new DocumentBuilder() .setTitle('My API') .setDescription('A comprehensive API for managing resources'); ``` -------------------------------- ### setLicense Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets the license information for the API. Returns `this` for method chaining. ```typescript const config = new DocumentBuilder() .setLicense('MIT', 'https://opensource.org/licenses/MIT'); ``` -------------------------------- ### DTO with Property Documentation Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Example of a DTO (Data Transfer Object) with property documentation using NestJS Swagger decorators. ```typescript import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; import { IsEmail, MinLength, IsOptional } from 'class-validator'; export class CreateUserDto { @ApiProperty({ description: 'User email address', example: 'user@example.com', format: 'email' }) @IsEmail() email: string; @ApiProperty({ description: 'User password (minimum 8 characters)', minLength: 8 }) @MinLength(8) password: string; @ApiPropertyOptional({ description: 'User phone number', example: '+1234567890' }) @IsOptional() phone?: string; } ``` -------------------------------- ### SwaggerCustomOptions Interface Source: https://github.com/nestjs/swagger/blob/master/_autodocs/types.md Configuration options for Swagger UI setup. ```typescript interface SwaggerCustomOptions { useGlobalPrefix?: boolean; swaggerUiEnabled?: boolean; // @deprecated ui?: boolean; raw?: boolean | Array<'json' | 'yaml'>; swaggerUrl?: string; jsonDocumentUrl?: string; yamlDocumentUrl?: string; patchDocumentOnRequest?: ( req: TRequest, res: TResponse, document: OpenAPIObject ) => OpenAPIObject | Promise; explorer?: boolean; swaggerOptions?: SwaggerUiOptions; customCss?: string; customCssUrl?: string | string[]; customJs?: string | string[]; customJsStr?: string | string[]; customfavIcon?: string; customSiteTitle?: string; customSwaggerUiPath?: string; validatorUrl?: string; // @deprecated url?: string; // @deprecated urls?: Record<'url' | 'name', string>[]; // @deprecated } ``` -------------------------------- ### getSchemaPath Example Usage Source: https://github.com/nestjs/swagger/blob/master/_autodocs/utility-functions.md Demonstrates how to use getSchemaPath with class references, string names, and custom schema names. ```typescript import { getSchemaPath } from '@nestjs/swagger'; // Using class reference getSchemaPath(UserDto) // Returns: '#/components/schemas/UserDto' // Using string name getSchemaPath('User') // Returns: '#/components/schemas/User' // With custom schema name via @ApiSchema decorator @ApiSchema({ name: 'UserResponse' }) export class UserDto {} getSchemaPath(UserDto) // Returns: '#/components/schemas/UserResponse' ``` -------------------------------- ### generateSchema Example Usage Source: https://github.com/nestjs/swagger/blob/master/_autodocs/utility-functions.md Shows how to use generateSchema to create an OpenAPI schema object from a DTO. ```typescript import { generateSchema } from '@nestjs/swagger'; export class CreateUserDto { @ApiProperty() email: string; @ApiProperty() name: string; } const schema = generateSchema(CreateUserDto); // Returns: // { // type: 'object', // properties: { // email: { type: 'string' }, // name: { type: 'string' } // }, // required: ['email', 'name'] // } ``` -------------------------------- ### Advanced Security Configuration Source: https://github.com/nestjs/swagger/blob/master/_autodocs/overview.md Example of advanced security configuration for the Swagger document builder, including Bearer, API Key, and OAuth2 authentication. ```typescript const config = new DocumentBuilder() .setTitle('Secured API') .addBearerAuth() .addApiKey({ type: 'apiKey', in: 'header', name: 'X-API-Key' }, 'api_key') .addOAuth2({ type: 'oauth2', flows: { implicit: { authorizationUrl: 'https://example.com/oauth/authorize', scopes: { 'read:api': 'Read access', 'write:api': 'Write access' } } } }, 'oauth2') .addSecurityRequirements('bearer') .build(); ``` -------------------------------- ### ApiHeader Decorator Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/decorators.md Shows how to use the @ApiHeader decorator to document request header parameters, including their name, description, and required status. ```typescript @Get() @ApiHeader({ name: 'X-API-Key', description: 'API key for authentication', required: true }) @ApiHeader({ name: 'X-Tenant-ID', description: 'Tenant identifier', required: true }) findAll( @Headers('X-API-Key') apiKey: string, @Headers('X-Tenant-ID') tenantId: string ) { return this.usersService.findAll(tenantId); } ``` -------------------------------- ### Plugin Benefits: Automatic Documentation Generation (Without Plugin) Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md Example of DTO class requiring explicit ApiProperty decorators without the plugin. ```typescript export class CreateUserDto { @ApiProperty({ description: 'User email' }) @IsEmail() email: string; @ApiProperty({ description: 'User password' }) @MinLength(8) password: string; } ``` -------------------------------- ### Plugin Benefits: Automatic Documentation Generation (With Plugin) Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md Example of DTO class where decorators are optional due to plugin's automatic description derivation from JSDoc. ```typescript export class CreateUserDto { @IsEmail() // Plugin derives description from JSDoc email: string; @MinLength(8) password: string; } ``` -------------------------------- ### Plugin Benefits: Automatic Controller Tagging Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md Example of a controller that will be automatically tagged based on its class name. ```typescript @Controller('users') export class UsersController { @Get() findAll() {} } // Automatically tagged as 'Users' ``` -------------------------------- ### DeepPartialType API Impact Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md Illustrates how a controller endpoint can utilize a DTO created with DeepPartialType for partial updates. ```typescript @Controller('users') export class UsersController { @Patch(':id') @ApiBody({ type: UpdateUserDeepDto }) updateDeep(@Param('id') id: string, @Body() updateDto: UpdateUserDeepDto) { // Can partially update nested objects if (updateDto.address?.city) { // Only update city if provided } } } ``` -------------------------------- ### setContact Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets the contact information for the API. Returns `this` for method chaining. ```typescript const config = new DocumentBuilder() .setContact('Support Team', 'https://support.example.com', 'support@example.com'); ``` -------------------------------- ### Polymorphic Responses with anyOf/oneOf Source: https://github.com/nestjs/swagger/blob/master/_autodocs/utility-functions.md Example demonstrating how to define polymorphic responses using `oneOf` and `discriminator` in NestJS Swagger. ```typescript import { getSchemaPath } from '@nestjs/swagger'; @Controller('notifications') export class NotificationsController { @Get() @ApiResponse({ status: 200, schema: { type: 'array', items: { oneOf: [ { $ref: getSchemaPath(EmailNotificationDto) }, { $ref: getSchemaPath(SmsNotificationDto) }, { $ref: getSchemaPath(PushNotificationDto) } ], discriminator: { propertyName: 'type', mapping: { email: getSchemaPath(EmailNotificationDto), sms: getSchemaPath(SmsNotificationDto), push: getSchemaPath(PushNotificationDto) } } } } }) getNotifications() { return this.notificationService.getAll(); } } ``` -------------------------------- ### setVersion Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets the version of the API specification. Returns `this` for method chaining. ```typescript const config = new DocumentBuilder() .setVersion('1.0.0'); ``` -------------------------------- ### Building Complex Response Schemas Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/utility-functions.md Demonstrates building complex response schemas with nested objects and arrays using getSchemaPath. ```typescript import { getSchemaPath } from '@nestjs/swagger'; @Controller('products') export class ProductsController { @Get() @ApiResponse({ status: 200, schema: { type: 'object', properties: { data: { type: 'array', items: { $ref: getSchemaPath(ProductDto) } }, pagination: { type: 'object', properties: { total: { type: 'number' }, page: { type: 'number' }, limit: { type: 'number' } } }, errors: { type: 'array', items: { $ref: getSchemaPath(ErrorDto) } } } } }) findAll( @Query('page') page: number = 1, @Query('limit') limit: number = 10 ) { return this.productsService.paginate(page, limit); } } ``` -------------------------------- ### setExternalDoc Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets external documentation for the API. Returns `this` for method chaining. ```typescript const config = new DocumentBuilder() .setExternalDoc('API Guide', 'https://docs.example.com/api-guide'); ``` -------------------------------- ### setTitle Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets the title of the API specification. Returns `this` for method chaining. ```typescript const config = new DocumentBuilder() .setTitle('My API'); ``` -------------------------------- ### IntersectionType API Impact Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/type-helpers.md Shows how a controller endpoint can use the combined DTO generated by IntersectionType. ```typescript @Controller('users') export class UsersController { @Post('complete') @ApiBody({ type: CompleteUserDto }) createComplete(@Body() completeUserDto: CompleteUserDto) { // Accepts all fields from all combined types return this.usersService.create(completeUserDto); } } ``` -------------------------------- ### ApiResponse Decorator Source: https://github.com/nestjs/swagger/blob/master/_autodocs/decorators.md Decorator to document a response for an operation, including status, description, type, and examples. ```typescript @ApiResponse(options: ApiResponseOptions, { overrideExisting }?: { overrideExisting: boolean }): MethodDecorator & ClassDecorator ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | ApiResponseOptions | Yes | — | Response metadata | | overrideExisting | boolean | No | true | Whether to override existing metadata | **ApiResponseOptions:** - `status`: HTTP status code (number, 'default', or range like '4XX') - `description`: Response description - `type`: Response body type (class, string, or [class] for arrays) - `isArray`: Whether response is an array - `example`: Example response value - `examples`: Multiple example responses - `schema`: Custom schema object - `nullable`: Whether response can be null ``` ```typescript @Get(':id') @ApiResponse({ status: 200, description: 'User found', type: UserDto }) @ApiResponse({ status: 404, description: 'User not found' }) findOne(@Param('id') id: string) { return this.usersService.findOne(+id); } ``` -------------------------------- ### Creating Custom Schema References Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/utility-functions.md Illustrates advanced schema usage for creating custom schema references using @ApiExtra and getSchemaPath. ```typescript import { getSchemaPath } from '@nestjs/swagger'; @ApiExtra('x-schema-variant', { schemaRef: getSchemaPath(UserDto) }) @Controller('users') export class UsersController { @Get() @ApiResponse({ status: 200, schema: { oneOf: [ { $ref: getSchemaPath(AdminUserDto) }, { $ref: getSchemaPath(RegularUserDto) } ] } }) findAll() { return this.usersService.findAll(); } } ``` -------------------------------- ### Plugin Benefits: TypeDoc Comments as Descriptions Source: https://github.com/nestjs/swagger/blob/master/_autodocs/plugin.md Example of DTO class using JSDoc comments for property descriptions, which the plugin converts to OpenAPI descriptions. ```typescript export class UserDto { /** * User's email address for login and communication */ email: string; /** * User's display name shown across the application * @example John Doe */ name: string; /** * User's age in years * @minimum 0 * @maximum 150 */ age: number; } ``` -------------------------------- ### ApiProduces Decorator Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/decorators.md Illustrates the @ApiProduces decorator for specifying the MIME types that an endpoint produces, allowing for content negotiation. ```typescript @Get('export') @ApiProduces('application/pdf', 'application/json') exportData(@Query('format') format: string = 'json') { if (format === 'pdf') { return this.usersService.exportPdf(); } return this.usersService.exportJson(); } ``` -------------------------------- ### ApiQuery Decorator Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/decorators.md Demonstrates how to use the @ApiQuery decorator to document query parameters for an endpoint, including specifying name, type, description, required status, enum values, and deprecation. ```typescript @Get() @ApiQuery({ name: 'limit', type: Number, description: 'Number of records', required: false }) @ApiQuery({ name: 'offset', type: Number, description: 'Number of records to skip', required: false }) @ApiQuery({ name: 'sort', type: String, enum: ['asc', 'desc'], required: false }) findAll( @Query('limit') limit: number = 10, @Query('offset') offset: number = 0, @Query('sort') sort: string = 'asc' ) { return this.usersService.findAll(limit, offset, sort); } ``` -------------------------------- ### setOpenAPIVersion Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets the OpenAPI specification version. Must follow semantic versioning format (x.x.x). Returns `this` for method chaining. Logs a warning if the version format is invalid. ```typescript const config = new DocumentBuilder() .setOpenAPIVersion('3.1.0'); ``` -------------------------------- ### ApiConsumes Decorator Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/decorators.md Demonstrates the @ApiConsumes decorator for specifying the MIME types that an endpoint can consume, particularly useful for file uploads. ```typescript @Post('upload') @ApiConsumes('multipart/form-data') @ApiBody({ schema: { type: 'object', properties: { file: { type: 'string', format: 'binary' } } } }) uploadFile(@UploadedFile() file: Express.Multer.File) { return { filename: file.filename }; } ``` -------------------------------- ### addServer Method Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Adds a server to the OpenAPI specification. Includes parameters for URL, description, variables, and custom properties. ```typescript addServer( url: string, description?: string, variables?: Record, serverExtraProperties?: Record ): this ``` ```typescript const config = new DocumentBuilder() .addServer('https://api.example.com', 'Production server') .addServer('https://staging.example.com', 'Staging server') .addServer('http://localhost:3000', 'Development server'); ``` -------------------------------- ### build Method Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Builds and returns the OpenAPI document configuration (without paths). ```typescript build(): Omit ``` ```typescript const config = new DocumentBuilder() .setTitle('My API') .setVersion('1.0.0') .build(); ``` -------------------------------- ### Constructor Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Creates a new DocumentBuilder instance. The document is initialized with default OpenAPI 3.0.0 base structure. ```typescript constructor() ``` -------------------------------- ### setTermsOfService Example Source: https://github.com/nestjs/swagger/blob/master/_autodocs/document-builder.md Sets the Terms of Service URL for the API. Returns `this` for method chaining. ```typescript const config = new DocumentBuilder() .setTermsOfService('https://example.com/terms'); ``` -------------------------------- ### Git Workflow for Pull Requests Source: https://github.com/nestjs/swagger/blob/master/CONTRIBUTING.md Standard shell commands for managing feature branches, committing changes, pushing to remote, and rebasing against the upstream master branch. ```shell git checkout -b my-fix-branch master git commit -a git push origin my-fix-branch git rebase master -i git push -f ```