NestJS导出API文档
在NestJS中,你可以使用@nestjs/swagger
包来定义你的API文档,并且可以很容易地将这些文档转换为API调用。以下是一个简单的例子,展示如何使用NestJS和Swagger来创建一个API文档,并且如何生成API调用。
首先,安装@nestjs/swagger
和swagger-ui-express
:
npm install @nestjs/swagger swagger-ui-express
然后,在你的NestJS模块中使用Api
和ApiOperation
装饰器来定义你的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应用程序中使用SwaggerModule
和DocumentBuilder
来配置和启动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文档,您可以在预览界面中对其进行进一步编辑和管理。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2006-12-14 控件不获得焦点