Combining definitions in Swagger documents

I am documenting an API with Swagger docs. I have several endpoints that share a common set of basic properties. I would like to use $ ref to reference this basic set of properties, and then expand these properties with additional properties that are unique to each endpoint. I imagined that it would work something like this, but this is not true:

"properties": { "$ref": "#/definitions/baseProperties", unique_thing": { "type": "string" }, "another_unique_thing": { "type": "string" } } 
+7
swagger swagger-ui
source share
1 answer

Indeed, the example given here is not valid, since $ref cannot coexist with other properties in the same object. $ref is a JSON reference and by definition ignores other properties.

Based on your question, I assume that you are looking for a basic composition (not inheritance). This is achievable with the allOf word allOf .

So, in the example you provided, you will get 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 an example in the specification .

+14
source share

All Articles