如何用nest生成一份swagger文档

52 阅读1分钟

首先新建项目

nest new swagget -p npm

然后安装nest/swagger

npm install --save @nestjs/swagger

然后在主入口文件main.ts里添加

 const documentConfig = new DocumentBuilder()
    .setTitle('swagger example')
    .setDescription('The API description')
    .setVersion('1.0')
    .addTag('swagger')
    .build();
  const document = SwaggerModule.createDocument(app, documentConfig);
  SwaggerModule.setup('doc', app, document);
  1. DocumentBuilder 创建 documentConfig。
  2. 然后用 SwaggerModule.createDocument 根据 config 创建文档。
  3. 之后用 SwaggerModule.setup 指定在哪个路径可以访问文档。

然后启动项目

pnpm run start:dev

访问 http://localhost:3000/doc 就可以看到 swagger 的 api 文档了:

让我们在生成一份 Rest API的接口文档

nest generate resource swaggerdemo

刷新页面就会看到最新的文档了

接着只要在每个controller添加对应的逻辑即可