安装 Swagger 模块:首先,使用 npm 或者 yarn 安装 @nestjs/swagger
模块。
npm install @nestjs/swagger swagger-ui-express
配置 Swagger 模块:在你的 NestJS 应用的根模块(通常是 app.module.ts
)中进行配置。
import { Module } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
constructor() {
const config = new DocumentBuilder()
.setTitle('Your API')
.setDescription('API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(this.app, config);
SwaggerModule.setup('api', this.app, document);
}
}
上述代码中,你需要调整 setTitle
、setDescription
和 setVersion
方法中的参数,以反映你自己的 API 标题、描述和版本。
在控制器类上添加装饰器:在每个控制器类上添加 @ApiTags()
装饰器,并指定与该控制器相关的标签。
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
@Controller('cats')
@ApiTags('cats') // 这里指定与该控制器相关的标签
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
在上述示例中,我们使用 @ApiTags()
装饰器将 CatsController
控制器与 "cats" 标签关联起来。
启动应用程序:启动你的 NestJS 应用程序,在浏览器中访问 /api
或者 /swagger
路径即可查看 Swagger UI 界面,并浏览和测试 API。
这样,你就成功将 Swagger 集成到了你的 NestJS 应用中。现在你可以使用 Swagger 自动生成的文档来描述和测试你的 API 接口。
这里只做了简单的集成,更多参数请看Swagger官方文档