DEV Community

Cover image for Merge and bundle open api yaml files for swagger
Mehdi Faraji
Mehdi Faraji

Posted on

Merge and bundle open api yaml files for swagger

Have you ever tried to document your apis with swagger?

The way you would approach after watching some tutorials and reading OPENAPI official documentation, is to code in a single yaml file and define components, schemas and etc all in one place.

In the end you will end up with hundreds of lines of code in a single file which is hard to read, not easy to modify or debug after a while.

And the only way to have a better development experience, is to use openapi's own SwaggerHub which is not free to use after all.

Not so good, right?

The better way to approach this situation is to have nicely named yaml files and folders and export them to use in a single yaml file.

Basically we will treat each schema or resource as a module and export it and then import each of them in a main file.

Then we would bundle and merge all files and build a single yaml file for our api documentation.

The structure I suggest is to create separate folders for parameters, resources, responses and schemas.

Finally you can bundle all of your yaml files with this command:

npx swagger-cli bundle src/openapi.yaml - outfile _build/openapi.yaml - type yaml
Enter fullscreen mode Exit fullscreen mode

The swagger-cli tool merges all of your yaml files into one file inside _build directory.

To test it out, you can copy the generated build file and paste it in Swagger live editor.

You can check how I've demonstrated the bundling on my Github repo.

Top comments (0)