12

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"
    }
 }
Bailey Smith
  • 2,853
  • 4
  • 27
  • 39

1 Answers1

31

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.

Helen
  • 87,344
  • 17
  • 243
  • 314
Ron
  • 14,160
  • 3
  • 52
  • 39