How to refer to enclosing type definition recursively in OpenAPI / Swagger?

11,570

Your definition is perfectly fine. It's a known issue issue with rendering recursive schemas in Swagger Editor and Swagger UI:

https://github.com/swagger-api/swagger-ui/issues/3325

To work around the "Example Value" showing null/"string"/undefined instead of a recursive element, you can add a custom example to your schema:

definitions:
  TreeNode:
    type: object
    properties:
      name:
        type: string
        description: The name of the tree node.
      children:
        type: array
        items:
          $ref: '#/definitions/TreeNode'
    example:
      name: foo
      children:
        - name: bar
        - name: baz
          children:
            - name: qux
Share:
11,570
Morten E. Rasmussen
Author by

Morten E. Rasmussen

Updated on June 28, 2022

Comments

  • Morten E. Rasmussen
    Morten E. Rasmussen almost 2 years

    I'm writing an OpenAPI definition in Swagger Editor.

    One of my type definitions contains an array containing child elements of the same type as the parent. I.e. something like this:

    definitions:
      TreeNode:
        type: object
        properties:
          name:
            type: string
            description: The name of the tree node.
          children:
            type: array
            items:
              $ref: '#/definitions/TreeNode'
    

    However, Swagger Editor doesn't pick up the recursive reference in the children array, which is simply shown as an array of "undefined" elements.

    Does anybody have an idea on how to do this?`