Home > Net >  How to split openAPI/Swagger file into multiple valid sub-files?
How to split openAPI/Swagger file into multiple valid sub-files?

Time:03-19

Our service implements different levels of access and we are using one openAPI YAML file internally.

For external documentation purposes, we would like to create multiple openAPI files, that are valid in themselves (self-sustained), but only have a partial set of the global file, e.g. based on the path or on tags.

(The same path may be used in different split-Files but I don't think that is a problem then.)

Any idea on how to achieve that? Is there some tooling around for it?

CodePudding user response:

You can use a valid URI in a JSON Pointer which points to another resource. The URI can be a path to a local file, a web resource, etc.:

paths:
  /user/{id}:
    summary: Get a user
    parameters:
      - $ref: "./path/to/file#/user_id"

# And so on...

Reserved keys in the OpenAPI spec must be unique so I don't think you'd be able to create standalone OpenAPI specs without some third-party utility that could overcome that limitation.

However, you would be able to create valid standalone JSON objects defined across many files and reference them in the index document. There are many articles online providing examples:

CodePudding user response:

I ended up writing a Python script, that I have posted here.

Flow

  1. Read the YAML File into a dictionary
  2. Copy the dictionary to a new dictionary
  3. Iterate through the original dictionary and
  4. Remove items that are not tagged with the tag(s) you want to keep
  5. Remove items that are have some keyword you want to omit in the path
  6. Write out the dictionary to a new YAML

The GIST is available here: https://gist.github.com/erikm30/d1f7e1cea3f18ece207ccdcf9f12354e

  • Related