I want to combine an API specification written using the OpenAPI 3 spec, that is currently divided into multiple files that reference each other using $ref
. How can I do that?
How to Merge OpenAPI 3 Files. `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.
Basic authentication. API key (as a header or query parameter) OAuth 2 common flows (implicit, password, application and access code)
One way to do this is to use the open-source project speccy.
Open the terminal and install speccy
by running (requires Node.js):
npm install speccy -g
Then run:
speccy resolve path/to/spec.yaml -o spec-output.yaml
Most OpenAPI tools can work with multi-file OpenAPI definitions and resolve $ref
s dynamically.
If you specifically need to get a single resolved file, Swagger Codegen can do this. Codegen has a CLI version (used in the examples below), a Maven plugin (usage example) and a Docker image.
The input file (-i
argument of the CLI) can be a local file or a URL.
Note: Line breaks are added for readability.
Use Codegen 3.x to resolve OpenAPI 3.0 files:
java -jar swagger-codegen-cli-3.0.35.jar generate
-l openapi-yaml
-i ./path/to/openapi.yaml
-o ./OUT_DIR
-DoutputFile=output.yaml
-l openapi-yaml
outputs YAML, -l openapi
outputs JSON.
-DoutputFile
is optional, the default file name is openapi.yaml
/ openapi.json
.
Use Codegen 2.x to resolve OpenAPI 2.0 files (swagger: '2.0'
):
java -jar swagger-codegen-cli-2.4.28.jar generate
-l swagger-yaml
-i ./path/to/openapi.yaml
-o ./OUT_DIR
-DoutputFile=output.yaml
-l swagger-yaml
outputs YAML, -l swagger
outputs JSON.
-DoutputFile
is optional, the default file name is swagger.yaml
/ swagger.json
.
I wrote a quick tool to do this recently. I call it openapi-merge. There is a library and an associated CLI tool:
In order to use the CLI tool you just write a configuration file and then run npx openapi-merge-cli
. The configuration file is fairly simple and would look something like this:
{
"inputs": [
{
"inputFile": "./gateway.swagger.json"
},
{
"inputFile": "./jira.swagger.json",
"pathModification": {
"stripStart": "/rest",
"prepend": "/jira"
}
},
{
"inputFile": "./confluence.swagger.json",
"disputePrefix": "Confluence",
"pathModification": {
"prepend": "/confluence"
}
}
],
"output": "./output.swagger.json"
}
For more details, see the README on the NPM package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With