Search code examples
swaggerswagger-uiapi-designopenapi

Swagger respond with associated objects


I'm using SwaggerHub with OpenAPI 3 to define an API. One route GET /foo/{id], should return the foo object of a given id, with its associated bar objects. The API will return something like: {id: 4, name: 'test', bars: [{id: 53, name: 'barName1'}, {id: 87, name: 'barName2'}]}. I.e. there is a many-to-many relationship between foo and bar.

How do I describe this in OpenAPI 3 syntax? I have tried using the anyOf property. So far I have:

paths:
  /foo/{id}:
    get:
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          content:
            application/json:
              schema:
                type: array
                items: 
                  $ref: '#/components/schemas/Foo'
                anyOf:
                  - $ref: '#/components/schemas/Bar'

But this doesn't appear to show the correct schema in the UI (there is no mention of Bar in the UI).


Solution

  • You don't need anyOf. anyOf indicates an alternative ("either Foo or Bar"), whereas you have a usual nested structure - an object Foo with the property bars that is an array of Bars. This can be described as:

          responses:
            '200':
              description: OK
              content:
                application/json:
                  schema:
                    $ref: '#/components/schemas/Foo'
    
    components:
      schemas:
        Foo:
          type: object
          properties:
            bars:
              type: array
              items:
                $ref: '#/components/schemas/Bar'
          required:
            - bars
        Bar:
          ...