Search code examples
swaggernestjsgoogle-cloud-endpointsopenapinestjs-swagger

Generate swagger 2.0 yaml using swagger 4.x package


I am going to integrate my API server to Google Cloud Endpoints.

And Google Cloud Endpoints supports swagger 2.0 as of now.

But my dependencies/libraries are up versions now. So I want to generate swagger 2.0 yaml file without downgrading swagger library version (api end points are already described with swagger 4.x - openapi 3.0 spec).

Nestjs and swagger dependencies (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",

...

And swagger generator script:

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()

And output of script is openapi 3.0 spec :(

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

...

Is there any option/way to generate swagger2.0 yaml from openapi 3.0 document?

How can I downgrade openapi 3.0 spec to swagger 2.0 spec?


Solution

  • I use this project from github for that very purpose: https://github.com/LucyBot-Inc/api-spec-converter

    For openapi 3 yaml to swagger 2 yaml, it's as simple as $ api-spec-converter --from openapi_3 --syntax yaml --to swagger_2 ${f} > ${SWAGGER_V2_FILE}