返回
NestJS 7.x 折腾记:Swagger 接入及用法全览
前端
2023-10-30 06:17:19
NestJS 与 Swagger 的强强联合
NestJS 是一个备受追捧的 Node.js 框架,以其模块化、可测试性和可扩展性而著称。Swagger 则是一个功能强大的 API 文档工具,可以轻松地生成美观且易于理解的 API 文档。将这两者结合使用,无疑如虎添翼,可显著提升 API 开发和维护的效率。
Swagger 接入 NestJS 的 3 步走
-
安装必要的依赖项
首先,我们需要在 NestJS 项目中安装 Swagger 的依赖项:
npm install @nestjs/swagger
-
注册 Swagger 模块
在 NestJS 模块中,导入并注册 Swagger 模块:
import { Module } from '@nestjs/common'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; @Module({}) export class AppModule { configure(consumer: MicroframeworkOptionsFactory) { const options = new DocumentBuilder() .setTitle('NestJS API') .setDescription('The description of your API') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(consumer, options); SwaggerModule.setup('api', consumer, document); } }
-
配置 Swagger 文档信息
通过 DocumentBuilder 配置 Swagger 文档的元数据,如标题、和版本等。
Swagger 用法探秘
-
生成 API 文档
在项目运行后,你可以在浏览器中输入
http://localhost:3000/api
来访问 Swagger 文档。 -
探索接口文档
Swagger 文档清晰地展示了 API 的接口信息,包括请求方法、路径、参数和响应格式等。
-
尝试代码生成
Swagger 还支持代码生成,可以自动生成多种语言的客户端代码,如 TypeScript、JavaScript、Python 等。
结语
NestJS 与 Swagger 的组合,无疑是 API 开发和维护的利器。通过 Swagger,你可以轻松地为你的 API 生成美观且易于理解的文档,从而提高开发效率和 API 的可维护性。赶快行动起来,将 Swagger 纳入你的 NestJS 项目中吧!