Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 672
Henrique Barcelos Avatar asked Oct 09 '14 21:10

Henrique Barcelos


People also ask

What is difference between Swagger and OpenAPI?

Although the terms once referred to the same thing, they can no longer be used interchangeably…even though some people still do. In 2021, OpenAPI refers to the industry-standard specification for RESTful API design. Swagger refers to a set of SmartBear tools.


1 Answers

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.

like image 161
Ron Avatar answered Nov 16 '22 23:11

Ron