Search code examples
arraysswaggeropenapi

OpenAPI 3.0 - how to merge/unwrap items from one array into another?


In OpenAPI 3.0, if I have two components that are arrays of similar types like so:

components:
  schemas:
    AquaticMammals:
      type: array
      items:
        anyOf:
          - $ref: '#/components/schemas/Dolphin'
          - $ref: '#/components/schemas/Otter'
          - $ref: '#/components/schemas/Seal'
          - $ref: '#/components/schemas/Beaver'
    LandMammals:
      type: array
      items:
        anyOf:
          - $ref: '#/components/schemas/Elephant'
          - $ref: '#/components/schemas/Bear'
          - $ref: '#/components/schemas/Monkey'
          - $ref: '#/components/schemas/Camel'

Is there a nice way to create an array containing all elements from both lists without having to maintain a copy of both lists in a third component?

I've tried a few variations on anyOf and allOf including this, but I end up with an array of arrays rather than a single array containing the elements of both arrays.

components:
  schemas:
    Mammals:
      type: array
      items:
        anyOf:
          - allOf:
            - $ref: '#/components/schemas/AquaticMammals'
          - allOf:
            - $ref: '#/components/schemas/LandMammalsMammals'

Essentially what I'm looking for is an OpenAPI 3.0 equivalent of a javascript spread operator.


Solution

  • This should work:

    components:
      schemas:
        Mammals:
          type: array
          items:
            anyOf:
              - $ref: '#/components/schemas/AquaticMammals/items'
              - $ref: '#/components/schemas/LandMammals/items'
    

    Alternatively, you can create named schemas for the initial anyOf lists, this will make referencing a bit easier.

    components:
      schemas:
        AquaticMammal:
          anyOf:
           - $ref: '#/components/schemas/Dolphin'
           - $ref: '#/components/schemas/Otter'
           - $ref: '#/components/schemas/Seal'
           - $ref: '#/components/schemas/Beaver'
        AquaticMammals:
          type: array
          items:
            $ref: '#/components/schemas/AquaticMammal'
    
        LandMammal:
          anyOf:
            - $ref: '#/components/schemas/Elephant'
            - $ref: '#/components/schemas/Bear'
            - $ref: '#/components/schemas/Monkey'
            - $ref: '#/components/schemas/Camel'
        LandMammals:
          type: array
          items:
            $ref: '#/components/schemas/LandMammal'
    
        Mammals:
          type: array
          items:
            anyOf:
              - $ref: '#/components/schemas/AquaticMammal'
              - $ref: '#/components/schemas/LandMammal'