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.
Install the CLI globally:
Run the conversion command:
This will output an
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:
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
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