Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to self in OpenAPI 3.0

I have a data model definition in OpenAPI 3.0, using SwaggerHub to display the UI. I want one of the properties of a model to be related, which is an array of properties of the same model.

    Foo:
      properties:
        title:
          type: string
        related:
          type: array
          items: 
            $ref: '#/components/schemas/Foo'

The parser doesn't seem to like this - the UI shows the related property as an empty array. Is this kind of self-reference possible in OpenAPI 3.0?

like image 286
GluePear Avatar asked Jun 20 '18 14:06

GluePear


People also ask

What is the difference between a path and an operation in the OpenAPI Specification?

In OpenAPI terms, paths are endpoints (resources), such as /users or /reports/summary/ , that your API exposes, and operations are the HTTP methods used to manipulate these paths, such as GET, POST or DELETE.

What is allOf in OpenAPI?

OpenAPI lets you combine and extend model definitions using the allOf keyword. allOf takes an array of object definitions that are used for independent validation but together compose a single object. Still, it does not imply a hierarchy between the models. For that purpose, you should include the discriminator .


1 Answers

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
like image 127
Helen Avatar answered Oct 23 '22 20:10

Helen