Lesson 31 / 34

API Documentation with Swagger

Generate interactive OpenAPI docs for a NestJS API with @nestjs/swagger, decorators and the Nest CLI plugin.

Set up Swagger

@nestjs/swagger builds an OpenAPI document from your controllers and DTOs and serves an interactive UI.

import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const config = new DocumentBuilder()
    .setTitle('Users API')
    .setVersion('1.0')
    .addBearerAuth()
    .build();
  SwaggerModule.setup('docs', app, SwaggerModule.createDocument(app, config));
  await app.listen(3000);
}

Describe DTO properties and operations with decorators.

export class CreateUserDto {
  @ApiProperty({ example: 'ada@example.com' })
  @IsEmail()
  email: string;
}

@ApiTags('users')
@Controller('users')
export class UsersController {
  @Post()
  @ApiCreatedResponse({ description: 'User created' })
  create(@Body() dto: CreateUserDto) {}
}

Enable the Nest CLI Swagger plugin to infer most DTO metadata automatically, and expose the docs UI only in non-production environments.