Swagger: How to have a property reference a model in OpenAPI 2.0 (i.e. nest the models)?

Henrique Barcelos picture Henrique Barcelos · Oct 9, 2014 · Viewed 13.8k times · Source

I'm having a hard time trying to figure out how I can nest models in OpenAPI 2.0.

Currently I have:

SomeModel:
 properties:
   prop1:
     type: string
   prop2:
     type: integer
   prop3:
     type:
       $ref: OtherModel

OtherModel:
  properties:
    otherProp:
      type: string   

I have tried many other ways:

prop3:
  $ref: OtherModel
# or
prop3:
  schema:
    $ref: OtherModel
# or
prop3:
  type:
    schema:
      $ref: OtherModel

None of the above seem to work.

However, with arrays works just fine:

prop3:
  type: array
  items:
    $ref: OtherModel

Answer

Ron picture Ron · Oct 16, 2014

The correct way to model it in OpenAPI 2.0 would be:

swagger: '2.0'
...

definitions:
  SomeModel:
    type: object
    properties:
      prop1:
        type: string
      prop2:
        type: integer
      prop3:
        $ref: '#/definitions/OtherModel'   # <-----

  OtherModel:
    type: object
    properties:
      otherProp:
        type: string

If you use OpenAPI 3.0, models live in components/schemas instead of definitions:

openapi: 3.0.1
...

components:
  schemas:
    SomeModel:
      type: object
      properties:
        prop1:
          type: string
        prop2:
          type: integer
        prop3:
          $ref: '#/components/schemas/OtherModel'   # <-----

    OtherModel:
      type: object
      properties:
        otherProp:
          type: string

Remember to add type: object to your object schemas because the type is not inferred from other keywords.