Refer to self in OpenAPI 3.0

自作多情 提交于 2019-12-05 22:33:17

Your definition is correct, it's just Swagger UI currently does not render circular-referenced definitions properly. See issue #3325 for details.

What you can do is add a model example, and Swagger UI will display this example instead of trying to generate an example from the definition.

    Foo:
      type: object
      properties:
        title:
          type: string
        related:
          type: array
          items: 
            $ref: '#/components/schemas/Foo'
      example:     # <-------
        title: foo
        related:
          - title: bar
          - title: baz
            related:
              - title: qux

Alternatively, you can add an example just for the related array:

    Foo:
      type: object
      properties:
        title:
          type: string
        related:
          type: array
          items: 
            $ref: '#/components/schemas/Foo'
          example:   # <--- Make sure "example" is on the same level as "type: array"
            - title: bar
            - title: baz
              related:
                - title: qux

I got tired of this pesky situation, so I went with no example at all and chose to get rid of the items property, add a description element and use an empty array instead:

Foo:
  type: object
  properties:
    title:
      type: string
    related:
      type: array
      description: Array of Foo elements
      example: []

You can achieve that by a proxy model:

    ...
    _MessageProxy:
      description: Message
      type: object
      required:
        - id
        - user
        - body
        - publishedAt
      properties:
        id:
          title: Message id
          type: string
          readOnly: true
          example: '595f4acf828b0b766ad11290'
        user:
          $ref: '#/components/schemas/User'
    Message:
      allOf:
        - $ref: '#/components/schemas/_MessageProxy'
        - type: object
          properties:
            parent:
              title: Parent
              readOnly: true
              allOf:
                - $ref: '#/components/schemas/_MessageProxy'
    ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!