Swagger: How to have a property reference a model in OpenAPI 2.0 (i.e. nest the models)?
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.
Here's another trick that works. This solution applies to OpenAPI 3 – the latest version of the OpenAPI Specification as the point of answering this question.
Here's how:
Say, I have a User
model with a State
enum. I defined the State
enum in a different schema and then referenced it in the User
schema.
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
first_name:
type: string
last_name:
type: string
password:
type: string
format: password
state:
$ref: '#/components/schemas/State'
State:
type: string
description: List of States
enum:
- State 1
- State 2
- State 3
- State 4
- State 5
Note that the enums were represented as arrays here, if you would love to represent them as hashes, check out this solution on Representing enum property in hash.
That's all.
I hope this helps