Search code examples
yamlswaggerapi-designopenapi

Open API inherited example data


I'm using OpenAPI 3.0 to define an API for a service I am building. I'm running into an issue reusing schema components inside other components. For example, I have a Note object which contains a Profile object of the person who created the note. This works as expected by referencing the Profile object using the $ref keyword. The issue is when showing the example there isn't any data for the profile, and if I place the ref in the example like below it includes the actual OpenAPI block of Profile not just the example data for the Profile component.

I'm wondering if there is a way of reusing components in other components and also reusing the example set on those components?

Ex:

FullNote:
  allOf:
    - $ref: '#/components/schemas/BaseNote'
    - type: object
      title: A single note response
      required:
      - id
      - dateCreated
      - profile
      properties:
        id:
          type: integer
          format: int32
        dateCreated:
          type: integer
          format: int64
        profile:
          type: object
          $ref: '#/components/schemas/Profile'
      example:
        id: 123456789
        dateCreated: 1509048083045
        profile:
          $ref: '#/components/schemas/Profile'

Solution

  • The example keyword (not to be confused with exampleS) does NOT support $ref. The whole example needs to be specified inline:

        FullNote:
          allOf:
            - $ref: '#/components/schemas/BaseNote'
            - type: object
              ...
              example:
                id: 123456789
                dateCreated: 1509048083045
                influencer:
                  prop1: value1  # <----
                  prop2: value2
    

    Alternatively, you can use property-level examples - in this case tools like Swagger UI will build the schema example from property examples.

        FullNote:
          allOf:
            - $ref: '#/components/schemas/BaseNote'
            - type: object
              ...
              properties:
                id:
                  type: integer
                  format: int32
                  example: 123456789      # <----
                dateCreated:
                  type: integer
                  format: int64
                  example: 1509048083045  # <----
                profile:
                  # This property will use examples from the Profile schema
                  $ref: '#/components/schemas/Profile'
        Profile:
          type: object
          properties:
            prop1:
              type: string
              example: value1   # <----