推荐答案
在 Nest.js 中使用 @nestjs/swagger 生成 API 文档的步骤如下:
安装依赖: 首先需要安装
@nestjs/swagger和swagger-ui-express依赖包。npm install @nestjs/swagger swagger-ui-express
配置 Swagger: 在
main.ts文件中配置 Swagger 文档。// www.javascriptcn.com code example 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('API 文档') .setDescription('API 文档描述') .setVersion('1.0') .addTag('cats') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap();使用装饰器: 在控制器和路由处理函数上使用 Swagger 装饰器来生成文档。
// www.javascriptcn.com code example import { Controller, Get, Post, Body } from '@nestjs/common'; import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger'; import { CreateCatDto } from './dto/create-cat.dto'; @ApiTags('cats') @Controller('cats') export class CatsController { @Get() @ApiOperation({ summary: '获取所有猫咪' }) @ApiResponse({ status: 200, description: '返回所有猫咪' }) findAll(): string { return 'This action returns all cats'; } @Post() @ApiOperation({ summary: '创建一只猫咪' }) @ApiResponse({ status: 201, description: '猫咪创建成功' }) create(@Body() createCatDto: CreateCatDto): string { return 'This action adds a new cat'; } }DTO 装饰器: 在 DTO 类上使用 Swagger 装饰器来生成请求体和响应体的文档。
// www.javascriptcn.com code example import { ApiProperty } from '@nestjs/swagger'; export class CreateCatDto { @ApiProperty() name: string; @ApiProperty() age: number; @ApiProperty() breed: string; }访问文档: 启动应用后,访问
http://localhost:3000/api即可查看生成的 API 文档。
本题详细解读
1. 安装依赖
@nestjs/swagger 是 Nest.js 官方提供的 Swagger 模块,用于生成 API 文档。swagger-ui-express 是 Swagger UI 的 Express 中间件,用于在浏览器中展示生成的文档。
2. 配置 Swagger
在 main.ts 文件中,通过 DocumentBuilder 配置 Swagger 文档的基本信息,如标题、描述、版本等。然后使用 SwaggerModule.createDocument 生成文档对象,并通过 SwaggerModule.setup 设置文档的访问路径。
3. 使用装饰器
在控制器和路由处理函数上使用 Swagger 装饰器来生成文档。常用的装饰器包括:
@ApiTags:为控制器添加标签。@ApiOperation:为路由处理函数添加操作描述。@ApiResponse:为路由处理函数添加响应描述。
4. DTO 装饰器
在 DTO 类上使用 @ApiProperty 装饰器来描述请求体或响应体的字段信息。这些信息会在 Swagger 文档中展示出来,帮助开发者理解 API 的输入输出。
5. 访问文档
配置完成后,启动应用并访问指定的路径(如 http://localhost:3000/api),即可在浏览器中查看生成的 API 文档。文档中会展示所有的 API 接口、请求参数、响应格式等信息,方便开发者调试和使用。