Runscope API Monitoring    Learn More →

How to Merge OpenAPI Definition Files

By Heitor Tashiro Sergent on .

thumbnail.jpg

I recently saw a Twitter thread that started with a simple question: how to combine multiple OpenAPI 3 definition files back together? One of the answers on that Twitter thread came from Mike Ralphson, and he pointed out that speccy, an open-source project, could help with that.

Now, you might ask yourself, why would someone want to merge an OpenAPI definition file back together? Isn't the point of separating it into multiple files to have better organization? Well, merging a definition file back together into a single one can be useful if you have tooling that doesn't support definition files with references and requires a single one to be uploaded, whether that is for documentation tooling, a UI definition editor, or maybe for API Gateway support.

speccy

speccy is an open-source project written in Node.js, that allows the user to lint, merge, and visualize an OpenAPI definition in a human-readable format.

For our purposes, we're just going to focus on the merging aspect of it.

How to Merge OpenAPI 3 Files

To use speccy, first we need to have Node.js installed in our machine. You can either download it from the Node.js website, or open the terminal and run:

curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg</a>.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/"

Then, we can install speccy by opening the terminal and running:

npm install -g speccy@0.8.7

And finally, still in the terminal, go to the directory where your OpenAPI definition files are and run:

speccy resolve spec.yaml -o spec-output.yaml

`resolve` is the command to merge definition files back into one. It's followed by the path to the main definition file that includes references to other files you wish to merge. Next, we add the option flag -o to output the resulting definition to a new file named spec-output.yaml.

If you want to test this on a definition file that's broken up into separate files but you don't have one at the moment, you can use this example I set up using the Pet Store example: https://github.com/heitortsergent/openapi3-ref-example

And if you're curious about the way I split up this OpenAPI definition, I used this great blog post by Jack Skinner as a reference: Maintaining large design-first API specs.

And you're all set.

Note: you might have noticed that we are using a specific version of speccy, 0.8.7, in the install command. At the time of writing, there was a known issue with the latest version where the output flag for the resolve command was not working. I would recommend using the latest version if that bug has been fixed. And always be kind to open-source maintainers. :)

Categories: openapi, tutorial

Everything is going to be 200 OK®