我已按照说明创建 Swagger 文档,现在可以使用 Swagger UI 获取我的文档。我还想将文档生成为 JSON 或 YAML,这样就可以轻松导入,例如Postman,但是我在
SwaggerModule
中找不到任何合适的方法,Swagger UI也没有任何导出按钮。
根据这个 github 问题,您可以将创建的 Swagger
document
字符串化,例如像这样将其写入文件系统:
const app = await NestFactory.create(ApplicationModule);
const options = new DocumentBuilder()
.setTitle("Title")
.setDescription("description")
.setVersion("1.0")
.build();
const document = SwaggerModule.createDocument(app, options);
fs.writeFileSync("./swagger-spec.json", JSON.stringify(document));
SwaggerModule.setup("/api", app, document);
await app.listen(80);
在 Nestjs v9
中测试假设文档路径如下
http://localhost:3000/docs
获取 JSON
http://localhost:3000/docs-json
获取 YAML
http://localhost:3000/docs-yaml
以及所示的写入磁盘的解决方案 (https://stackoverflow.com/a/51736406/5693245),您仍然可以在自己的 API 端点上进行访问。
根据 docs,根据您是使用
swagger-ui-express
还是 fastify
来提供文档,位置会有所不同
要生成并下载 Swagger JSON 文件,请在浏览器中导航到 http://localhost:3000/api-json (swagger-ui-express) 或 http://localhost:3000/api/json (fastify-swagger) (假设您的 Swagger 文档位于 http://localhost:3000/api 下)。
这还取决于您从何处提供 API,并假设您使用
/api
。如果不是这种情况,请替换为您的端点,或者如果您没有使用 swagger-ui-express
的基本 URL,则这将是 http://localhost:3000/-json
在 Nestjs v8 中测试
GET http://{host}:{port}/docs
获取 JSON
GET http://{host}:{port}/docs/json
使用 NestJS 的最新版本(截至撰写时为 v8),按照 openapi 文档中的设置,您应该能够访问 json 文档,而无需使用
进行任何额外设置GET http://{host}:{port}/api-docs
我需要生成开放 API json 文件,而不需要我的应用程序所具有的数据库、网络服务器等依赖项。所以我编写了另一个 main.ts 文件(实际上我将其命名为 main-generate-swagger.ts)。 此 main-generate-swagger.ts 文件仅用于生成 json 文件。请勿在生产环境中运行!
主要生成-swagger.ts:
import { NestFactory } from '@nestjs/core';
import fs from 'fs/promises';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app/app.module';
async function bootstrap() {
const app = await NestFactory.create(
AppModule,
{ preview: true, abortOnError: false } // <-- This parameters prevent for instantiate controllers but its not necessary for SwaggerModule
);
const prefix = 'api/v1';
const corsOrigin = '*';
app.enableCors({ origin: corsOrigin });
app.setGlobalPrefix(prefix);
const config = new DocumentBuilder().setTitle('Toggl Fakturoid API').setDescription('Toggl Fakturoid').setVersion('1.0').addBearerAuth().build();
const document = SwaggerModule.createDocument(app, config);
await fs.writeFile('path/to/create/swagger.json', JSON.stringify(document));
process.exit();
}
bootstrap();
现在我不再运行 main.ts 文件,而是运行新的 main-generate-swagger.ts。它生成 json 文件并退出。
备注: