Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining defintions in Swagger docs

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"
    }
 }
like image 247
Bailey Smith Avatar asked Apr 05 '15 23:04

Bailey Smith


People also ask

What are Swagger definitions?

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.

What does schema mean in Swagger?

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).


1 Answers

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.

like image 66
Ron Avatar answered Oct 09 '22 14:10

Ron