Nest 中使用Swagger自动化API文档生成
1. 基础概念与使用
OpenAPI 规范是一种与语言无关的定义格式,用于描述 RESTful APIs。Nest 提供了一个专门的模块,通过装饰器,可以自动生成符合 OpenAPI 规范的文档。
首先,我们需要安装生成文档的必要依赖:
$ npm install --save @nestjs/swagger
在安装完成之后,打开 main.ts 文件,使用 SwaggerModule 类初始化 Swagger。
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';async function bootstrap() {const app = await NestFactory.create(AppModule);const config = new DocumentBuilder().setTitle('Cats example').setDescription('The cats API description').setVersion('1.0').addTag('cats').build();const document = SwaggerModule.createDocument(app, config);SwaggerModule.setup('api', app, document);await app.listen(3000);
}
bootstrap();
-
DocumentBuilder 帮助我们构建一个符合 OpenAPI 规范的基本文档。通过其方法可以设置标题、描述、版本等属性。
-
SwaggerModule.createDocument() 方法生成包含所有 HTTP 路由定义的完整文档。
-
SwaggerModule.setup() 用于将 Swagger UI 安装在指定的路径上,接收的参数包括路径、应用实例和生成的文档对象。
运行以下命令启动 HTTP 服务器:
$ npm run start
在应用运行时,打开浏览器并访问 http://localhost:3000/api 查看 Swagger UI。
2. Swagger JSON 文件生成
你还可以生成并下载 Swagger JSON 文件。默认情况下,它位于 http://localhost:3000/api-json,你还可以通过SwaggerModule.setup() 方法自定义路径,如下所示:
SwaggerModule.setup('swagger', app, document, {jsonDocumentUrl: 'swagger/json',
});
该设置将 Swagger JSON 文件暴露在 http://localhost:3000/swagger/json。
在 NestJS 项目中,@nestjs/swagger 提供了多种注解用于配置 API 文档。结合你提供的示例项目 (NestJS Swagger 示例项目),我们可以进一步扩展 Swagger 注解的配置使用。
以下是一些常见的 Swagger 注解配置用法及代码示例,以便更好地完善自动化 API 文档生成功能。
3. Swagger 注解使用及代码示例
3.1. @ApiTags() - 为控制器打标签
用于给控制器或特定的路由分配标签,这些标签会显示在 Swagger UI 中的侧边栏。
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';@ApiTags('cats')
@Controller('cats')
export class CatsController {@Get()findAll() {return 'This action returns all cats';}
}
3.2. @ApiOperation() - 路由的描述信息
可以给每个操作添加简短的描述,展示在 Swagger UI 中。
import { Controller, Get } from '@nestjs/common';
import { ApiOperation } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get()@ApiOperation({ summary: 'Get all cats' })findAll() {return 'This action returns all cats';}
}
3.3. @ApiResponse() - 定义响应状态及描述
用来为操作指定响应状态码及其描述。
import { Controller, Get } from '@nestjs/common';
import { ApiResponse } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get()@ApiResponse({ status: 200, description: 'Successful retrieval of cat list.' })@ApiResponse({ status: 404, description: 'Cats not found.' })findAll() {return 'This action returns all cats';}
}
3.4. @ApiParam() - 定义 URL 路径参数
用于定义 API 路径参数的相关信息。
import { Controller, Get, Param } from '@nestjs/common';
import { ApiParam } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get(':id')@ApiParam({ name: 'id', required: true, description: 'ID of the cat to retrieve' })findOne(@Param('id') id: string) {return `This action returns a cat with id: ${id}`;}
}
3.5. @ApiQuery() - 定义查询参数
用于描述请求中的查询参数及其属性。
import { Controller, Get, Query } from '@nestjs/common';
import { ApiQuery } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get()@ApiQuery({ name: 'age', required: false, description: 'Filter cats by age' })findAll(@Query('age') age: number) {return `This action returns all cats with age: ${age}`;}
}
3.6. @ApiBody() - 定义请求体
用来描述 POST、PUT 等请求中的请求体内容。
import { Controller, Post, Body } from '@nestjs/common';
import { ApiBody } from '@nestjs/swagger';class CreateCatDto {name: string;age: number;breed: string;
}@Controller('cats')
export class CatsController {@Post()@ApiBody({description: 'Details of the cat to create',schema: {type: 'object',properties: {name: { type: 'string' },age: { type: 'integer' },breed: { type: 'string' }}}})create(@Body() createCatDto: CreateCatDto) {return `This action adds a new cat with name: ${createCatDto.name}`;}
}
3.7. @ApiProperty() - 定义 DTO 中的属性
通常用于描述 DTO 类的属性,帮助生成 API 请求和响应的定义。
import { ApiProperty } from '@nestjs/swagger';export class CreateCatDto {@ApiProperty({ description: 'The name of the cat' })name: string;@ApiProperty({ description: 'The age of the cat', example: 3 })age: number;@ApiProperty({ description: 'The breed of the cat' })breed: string;
}
3.8. @ApiBearerAuth() - 为 API 添加认证信息
用于指定操作需要认证的接口。
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';@Controller('cats')
export class CatsController {@Get('protected')@UseGuards(AuthGuard('jwt'))@ApiBearerAuth()getProtectedData() {return 'This action returns protected data';}
}
3.9. @ApiExtraModels() 和 @ApiExcludeEndpoint()
@ApiExtraModels() 可用于引用额外的模型,而 @ApiExcludeEndpoint() 可用于在 Swagger 中隐藏某些路由。
import { ApiExtraModels, ApiExcludeEndpoint } from '@nestjs/swagger';
import { Controller, Get } from '@nestjs/common';class CatDetails {name: string;age: number;
}@ApiExtraModels(CatDetails)
@Controller('cats')
export class CatsController {@Get('hidden')@ApiExcludeEndpoint()getHidden() {return 'This route is hidden from Swagger';}
}
4. 补充资料
-
Nestjs 集成第三方模块示例:https://docs.nestjs.com/techniques/caching#different-stores
-
Nestjs 继承 ORM:https://docs.nestjs.com/techniques/database
-
Nestjs 定时任务:https://docs.nestjs.com/techniques/task-scheduling
-
集成 Kafka:https://docs.nestjs.com/microservices/kafka
-
接口文档生成:https://docs.nestjs.com/openapi/introduction
-
身份鉴权:https://docs.nestjs.com/security/authentication
-
访问控制:https://docs.nestjs.com/security/rate-limiting
-
官方 Devtools:https://docs.nestjs.com/devtools/overview