NestJS导出API文档

在NestJS中,你可以使用@nestjs/swagger包来定义你的API文档,并且可以很容易地将这些文档转换为API调用。以下是一个简单的例子,展示如何使用NestJS和Swagger来创建一个API文档,并且如何生成API调用。

首先,安装@nestjs/swaggerswagger-ui-express

npm install @nestjs/swagger swagger-ui-express

然后,在你的NestJS模块中使用ApiApiOperation装饰器来定义你的API文档:

复制代码
import { Controller, Get, Post } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
 
@Controller('cats')
@ApiTags('cats')
export class CatsController {
  @Get()
  @ApiOperation({ summary: 'Get all cats' })
  findAll(): string {
    return 'This action returns all cats';
  }
 
  @Post()
  @ApiOperation({ summary: 'Create a cat' })
  create(): string {
    return 'This action creates a cat';
  }
}
复制代码

最后,在你的NestJS应用程序中使用SwaggerModuleDocumentBuilder来配置和启动Swagger:

复制代码
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
 
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
 
  const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
 
  await app.listen(3000);
}
bootstrap();
复制代码

现在,当你运行你的NestJS应用程序并访问http://localhost:3000/docs时,你将会看到Swagger UI,它根据你在代码中定义的API文档展示出来。你可以直接点击API操作下的"Try it out"按钮来发起API调用,并查看响应。这样,你就可以将API文档转换为实际的API调用。

按“F12”或“Ctrl+Shift+I”打开浏览器控制台,然后导航到网络->Fetch/XHR并刷新页面。这应该会显示一个.json文件,您可以在新窗口中打开并下载。
如果没有.json文件,可以下载swagger-ui-init.js文件,取得 "swaggerDoc"部分另存为.json文件。

打开Apidog,导航到您的项目,然后选择项目设置->导入数据->OpenAPI/Swagger。上传之前导出的.yaml或.json文件。如果您有一个可公开访问的源文件URL,您也可以通过该URL导入它。
上传后,Apidog将自动解析并导入您的API文档,您可以在预览界面中对其进行进一步编辑和管理。

点击右上角即可分享
微信分享提示