Vanja Ćosić

Working with OpenAPI YAML specifications in JS

Specifications for web APIs that follow the OpenAPI standard (formerly known as Swagger) can be written as both YAML and JSON files. But some tools require the spec to be provided as JSON.

I faced that situtation while working on a client project this week and wanted to share how to do so.

In the command line #

We can use js-yaml as a command-line interface to convert the file.

  1. Install the CLI globally:

    Terminal
    npm install -g js-yaml
  2. Run the conversion command:

    Terminal
    js-yaml api.yaml

    This will output an api.json file.

Programmatically #

For our purposes we wanted to handle conversion and parsing inside our Node.js app, so I chose a programmatic approach instead of using the CLI.

Here’s a simplified example:

JS
import yaml from 'js-yaml'
import fs from 'fs'

try {
    // Read the YAML file as string
    const specAsYaml = fs.readFileSync('./api.yaml', 'utf8')
    
    // Parse YAML
    const specAsJsObject = yaml.load(specAsYaml)

    // Convert object to JSON
    const specAsJSON = JSON.stringify(specAsJsObject, null, 2)

    // Write the JSON to a file
    fs.writeFileSync('./api.json', specAsJSON)
} catch (e) {
    throw new Error(e)
}

The project uses the swagger-js client to parse the spec and generate documentation. So the YAML spec we converted above can be passed to the SwaggerClient constructor:

JS
import SwaggerClient from 'swagger-client'

// [...]

const client = await SwaggerClient({ spec: specAsJsObject })

A word of warning #

YAML is complex and has many pitfalls. See The yaml document from hell by Ruud van Asseldonk, which outlines some of them.

The short version:
Don’t parse untrusted YAML documents.

There have been numerous exampes of remote code execution vulnerabilities in YAML parsers in different programming languages. See if the one you are using has a safe method.