Skip to content

Swagger API文档

环境信息:Node.js 20.x、@nestjs/swagger 7.x、swagger-ui-express 5.x

为什么需要 API 文档#

后端开发完接口之后,前端需要知道接口的路径、请求方法、参数格式、响应格式等信息。传统方式是手动编写文档,但这样存在几个问题:

Swagger(OpenAPI)可以根据代码自动生成 API 文档,并提供在线调试功能。

安装配置#

创建项目并安装依赖:

Terminal window
nest n nest-swagger -g -p pnpm
pnpm add @nestjs/swagger swagger-ui-express -S

main.ts 中配置 Swagger:

import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
const config = new DocumentBuilder()
.setTitle('API 文档')
.setDescription('NestJS API 接口文档')
.setVersion('1.0')
.addBearerAuth()
.build()
const document = SwaggerModule.createDocument(app, config)
SwaggerModule.setup('api-docs', app, document)
await app.listen(3000)
}
bootstrap()

启动服务后访问 http://localhost:3000/api-docs 即可看到 Swagger UI 界面。

常用装饰器#

@ApiTags#

用于对接口进行分组:

import { Controller, Get } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
@ApiTags('用户模块')
@Controller('user')
export class UserController {
@Get()
findAll() {
return []
}
}

@ApiOperation#

描述接口的作用:

import { ApiOperation } from '@nestjs/swagger'
@Get()
@ApiOperation({ summary: '获取用户列表', description: '返回所有用户信息' })
findAll() {
return []
}

@ApiProperty#

描述 DTO 中的字段:

import { ApiProperty } from '@nestjs/swagger'
export class CreateUserDto {
@ApiProperty({ description: '用户名', example: 'jack' })
name: string
@ApiProperty({ description: '年龄', example: 25, minimum: 0, maximum: 150 })
age: number
@ApiProperty({ description: '邮箱', required: false })
email?: string
}

@ApiQuery 和 @ApiParam#

描述查询参数和路径参数:

import { ApiQuery, ApiParam } from '@nestjs/swagger'
@Get(':id')
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiQuery({ name: 'include', description: '包含关联数据', required: false })
findOne(@Param('id') id: number, @Query('include') include?: string) {
return { id }
}

@ApiResponse#

描述响应格式:

import { ApiResponse } from '@nestjs/swagger'
@Post()
@ApiResponse({ status: 201, description: '创建成功' })
@ApiResponse({ status: 400, description: '参数错误' })
create(@Body() createUserDto: CreateUserDto) {
return { id: 1, ...createUserDto }
}

认证配置#

如果接口需要 JWT 认证,可以添加 Bearer Token 支持:

// main.ts 中已添加 .addBearerAuth()
// 在 Controller 中使用
import { ApiBearerAuth } from '@nestjs/swagger'
@ApiBearerAuth()
@Controller('user')
export class UserController {
// ...
}

这样在 Swagger UI 中就会出现 Authorize 按钮,可以输入 Token 进行测试。

自动生成 DTO 文档#

配合 class-validator 使用时,可以通过插件自动读取验证规则:

Terminal window
pnpm add class-validator class-transformer -S

nest-cli.json 中启用插件:

{
"compilerOptions": {
"plugins": ["@nestjs/swagger"]
}
}

启用插件后,DTO 中的属性会自动识别类型,不需要显式写 @ApiProperty()

export class CreateUserDto {
// 自动识别为 string 类型
name: string
// 自动识别为 number 类型
age: number
}

导出文档#

可以将 Swagger 文档导出为 JSON 格式,方便与其他工具集成:

import { writeFileSync } from 'fs'
const document = SwaggerModule.createDocument(app, config)
writeFileSync('./swagger.json', JSON.stringify(document, null, 2))

导出的 JSON 文件可以导入到 Postman、Apifox 等工具中使用。