I'm documenting an API with Swagger docs. I have several endpoints that share a common set of base properties. I'd like to use $ref to refer to that base set of properties and then extend those properties with additional properties that are unique to each endpoint. I imagined that it would work something like this, but this is invalid:
"properties": {
"$ref": "#/definitions/baseProperties",
unique_thing": {
"type": "string"
},
"another_unique_thing": {
"type": "string"
}
}
Swagger is an open source set of rules, specifications and tools for developing and describing RESTful APIs. The Swagger framework allows developers to create interactive, machine and human-readable API documentation.
The schema keyword is used to describe the response body. A schema can define: an object or an array — typically used with JSON and XML APIs, a primitive data type such as a number or string – used for plain text responses, a file – (see below).
Indeed, the example you give here is invalid because $ref
can't co-exist with other properties in the same object. $ref
is a JSON Reference, and by definition, will cause the other properties to be ignored.
From your question, I assume you're looking for basic composition (rather than inheritance). This is achievable using the allOf
keyword.
So, with the example you provided, you would have something like this:
{
"baseProperties": {
"type": "object",
"properties": {
...
}
},
"complexModel": {
"allOf": [
{
"$ref": "#/definitions/baseProperties"
},
{
"type": "object",
"properties": {
"unique_thing": {
"type": "string"
},
"another_unique_thing": {
"type": "string"
}
}
}
]
}
}
YAML version:
definitions:
baseProperties:
type: object
properties:
...
complexModel:
allOf:
- $ref: '#/definitions/baseProperties'
- type: object
properties:
unique_thing:
type: string
another_unique_thing:
type: string
You can also check out the example in the spec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With