OpenAPI Schema Nested Models (more than 1 level)

Using OpenAPI 3+ and Redoc, and having issues with references not working once I go more than one level deep, is there something i’m doing wrong or missing here?

openapi.yaml

components:
  schemas:
    $ref: components/schemas/_index.yaml

components/schemas/_index.yaml

AdminParticipants:
  $ref: ./admin/Participants.yaml
admin:
  $ref: "./admin/_index.yaml"

components/schemas/admin/_index.yaml

Participants:
  $ref: ./Participants.yaml

When trying to access the schema model using below reference it does not work (get Invalid reference token: Participants error)

$ref: "#/components/schemas/admin/Participants"

However this does work:

$ref: "#/components/schemas/AdminParticipants"

Is it not possible to create nested references more than one level deep for schemas or any other components?

>Solution :

OpenAPI does not actually support $ref directly under the components.schemas node. You can only $ref individual schemas or schema properties. Some tools might accept $refs in arbitrary places, but the behavior may vary.

Here’s the version that will work with any OpenAPI-compliant tools:

# openapi.yaml

components:
  schemas:
    AdminParticipants:
      $ref: ./admin/Participants.yaml
    AnotherSchema:
      $ref: ./path/to/schema.yaml

You’ll can then reference these schemas as:

$ref: '#/components/schemas/AdminParticipants'

$ref: '#/components/schemas/AnotherSchema'

The following will NOT work – not only because of non-standard $ref placement in openapi.yaml, but also because it would result in a wrong structure of the schemas section.

# openapi.yaml

components:
  schemas:
    $ref: components/schemas/_index.yaml
# components/schemas/_index.yaml

admin:
  $ref: "./admin/_index.yaml"
# components/schemas/admin/_index.yaml

Participants:
  $ref: ./Participants.yaml

After dereferencing, the above snippets become:

components:
  schemas:
    admin:
      Participants:
        type: object  # or however the schema is defined in 'Participants.yaml'
        ...

which has an extra key between the schema name and schema contents, so it’s not valid OpenAPI.

Leave a Reply