NestJS 集成 Swagger(OpenAPI)
目的
为 REST API 自动生成 OpenAPI 文档,便于前端联调、测试与对外交付;Nest 官方推荐 @nestjs/swagger。
安装
bash
pnpm add @nestjs/swagger最小接入(main.ts)
typescript
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
const config = new DocumentBuilder()
.setTitle('API')
.setDescription('服务描述')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document); // 访问 /api-docs控制器与 DTO
- 使用
@ApiTags()、@ApiOperation()标注模块与接口说明。 - DTO 上使用
@ApiProperty(),便于生成请求体 / 响应 Schema。 - JWT 等认证使用
@ApiBearerAuth()与全局addBearerAuth()对齐。
生产环境
默认建议在 非生产 或 内网 暴露文档;生产可通过环境变量关闭 SwaggerModule.setup 或使用网关鉴权保护 /api-docs。
