如何在NestJS项目中集成Swagger来自动生成API文档?具体步骤是什么?

如何在NestJS项目中集成Swagger来自动生成API文档?具体步骤是什么?

我尝试在NestJS项目中使用@nestjs/swagger模块,但生成的文档缺少部分接口描述,该怎么解决?如何正确使用装饰器来完善API文档的元数据?

对于复杂的DTO对象,Swagger能否自动生成对应的Schema?如果需要自定义Schema,应该如何配置?

在实际项目中,如何为不同环境的API文档设置不同的访问路径?比如开发环境和生产环境使用不同的文档地址。

3 回复

要使用Swagger为NestJS项目生成API文档,首先确保安装了@nestjs/swaggerswagger-ui-express。在main.ts中引入并配置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);

  // 配置Swagger
  const config = new DocumentBuilder()
    .setTitle('API 文档')
    .setDescription('API 描述')
    .setVersion('1.0')
    .addTag('example')  // 标签
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);  // 在/docs路径展示

  await app.listen(3000);
}
bootstrap();

在需要生成文档的Controller上使用装饰器:

import { Controller, Get, Param, Query, SwaggerResponse } from '@nestjs/swagger';

@Controller('example')
export class ExampleController {
  @Get()
  @ApiOperation({ summary: '获取示例数据' })
  @ApiResponse({ status: 200, description: '成功' })
  getExample(@Query() params: any) {
    return { data: params };
  }
}

运行项目后访问/docs即可查看自动生成的API文档。记得在生产环境中禁用Swagger。


要使用Swagger为NestJS生成API文档,首先安装必要的依赖:

npm install @nestjs/swagger swagger-ui-express --save

然后在 AppModule 中配置 Swagger:

import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

@Module({
  imports: [],
})
export class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle('API 文档')
    .setDescription('我的API接口文档')
    .setVersion('1.0')
    .addTag('example')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();

接下来,在控制器中添加装饰器来描述接口:

import { Controller, Get, Param, Query } from '@nestjs/common';
import { ApiOperation, ApiParam, ApiQuery, ApiResponse } from '@nestjs/swagger';

@Controller('example')
export class ExampleController {
  @Get(':id')
  @ApiOperation({ summary: '获取示例数据' })
  @ApiParam({ name: 'id', description: '示例ID', required: true })
  @ApiResponse({ status: 200, description: '成功' })
  getExample(@Param('id') id: string) {
    return { id };
  }
}

最后运行项目,访问 http://localhost:3000/api 即可查看生成的API文档。

NestJS 使用 Swagger 生成 API 文档指南

安装必要依赖

首先安装 Swagger 模块:

npm install --save @nestjs/swagger

基本配置

main.ts 中配置 Swagger:

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

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);
}

在控制器中使用装饰器

为你的控制器和路由添加 Swagger 注释:

import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';

@ApiTags('cats')
@Controller('cats')
export class CatsController {
  @ApiOperation({ summary: '创建猫咪' })
  @ApiResponse({ status: 201, description: '创建成功' })
  @ApiResponse({ status: 403, description: '禁止访问' })
  @Post()
  create() {
    return 'This action adds a new cat';
  }

  @ApiOperation({ summary: '获取所有猫咪' })
  @Get()
  findAll() {
    return 'This action returns all cats';
  }
}

定义 DTO 模型

为请求和响应定义模型:

import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty({ example: 'Kitty', description: '猫咪名字' })
  name: string;

  @ApiProperty({ example: 1, description: '猫咪年龄' })
  age: number;
  
  @ApiProperty({ example: '波斯猫', description: '猫咪品种' })
  breed: string;
}

访问 Swagger UI

启动应用后,访问 http://localhost:3000/api 即可看到 Swagger UI 界面。

高级功能

  1. 认证
const config = new DocumentBuilder()
  .addBearerAuth()
  .build();
  1. 文件上传
@ApiConsumes('multipart/form-data')
@ApiBody({
  schema: {
    type: 'object',
    properties: {
      file: {
        type: 'string',
        format: 'binary',
      },
    },
  },
})
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file) {
  console.log(file);
}

这样你就可以为你的 NestJS 应用生成完整的 API 文档了。

回到顶部