使用swagger 4.x包生成swagger 2.0 yaml

时间:2020-06-18 22:53:57

标签: swagger nestjs google-cloud-endpoints openapi nestjs-swagger

我将把我的API服务器集成到Google Cloud Endpoints。

Google Cloud Endpoints到目前为止支持swagger 2.0。

但是我的依赖项/库现在是最新版本。因此,我想在不降级swagger库版本的情况下生成swagger 2.0 yaml文件(api端点已经使用swagger 4.x-openapi 3.0规范进行了介绍。)

Nestjs和swagger依赖项(package.json):

...

"@nestjs/common": "^7.0.0",
"@nestjs/config": "^0.4.0",
"@nestjs/core": "^7.0.0",
"@nestjs/platform-express": "^7.0.0",
"js-yaml": "^3.14.0",

...

"@nestjs/swagger": "^4.5.4",
"swagger-ui-express": "^4.1.4",

...

和招摇发电机脚本:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as fs from 'fs'
import * as yaml from 'js-yaml'

const generateSwaggerYaml = async () => {
  const app = await NestFactory.create(AppModule);
  const options = new DocumentBuilder()
    .setTitle('API Title')
    .setDescription('API Description')
    .build()

  const document = SwaggerModule.createDocument(app, options)

  fs.writeFileSync("./openapi-run.yaml", yaml.safeDump(document))
}


generateSwaggerYaml()

脚本的输出是openapi 3.0 spec:(

openapi: 3.0.0
info:
  title: API Title
  description: API Description.
  version: 1.0.0
  contact: {}
tags: []
servers: []

...

是否有任何选项/方法可以从openapi 3.0文档生成swagger2.0 yaml?

如何将openapi 3.0规范降级为swagger 2.0规范?

1 个答案:

答案 0 :(得分:2)

我将github中的这个项目用于此目的:https://github.com/LucyBot-Inc/api-spec-converter

对于openapi 3 yaml到2 yaml来说,它就像$ api-spec-converter --from openapi_3 --syntax yaml --to swagger_2 ${f} > ${SWAGGER_V2_FILE}一样简单