16

I am defining common schemas for Web services and I want to import them in the components/schema section of the specification. I want to create a canonical data model that is common across multiple services to avoid redefining similar objects in each service definition.

Is there a way to do this? Is there a similar mechanism to what XSD does with its import tag?

Aldo
  • 163
  • 1
  • 1
  • 5

2 Answers2

18

To expand on Helen's answer for those landing here from Google, if Pet.yaml is not a plain object but has several objects like this:

components:
  schemas:
    pet:
      type: object
      properties:
        (...)

You can refer to it like this:

$ref: './common/Pet.yaml#/components/schemas/pet'
ardal
  • 1,537
  • 3
  • 14
  • 18
  • But what if I want to include a document instead of referencing a document? There is a difference. I don't want to click. This problem has also been addressed within XML (XLink). I was hoping to see something similar in the OpenAPI standard. – Rudolf Mar 16 '20 at 08:01
  • 1
    What do you mean by "I don't want to click"? – Alp Jul 27 '21 at 18:35
16

You can $ref external OpenAPI schema objects directly using absolute or relative URLs:

responses:
  '200':
    description: OK
    schema:
      $ref: './common/Pet.yaml'
      # or
      # $ref: 'https://api.example.com/schemas/Pet.yaml'

where Pet.yaml contains, for example:

type: object
properties:
  id:
    type: integer
    readOnly: true
  petType:
    type: string
  name:
    type: string
required:
  - id
  - petType
  - name

See Using $ref for more information.

Helen
  • 87,344
  • 17
  • 243
  • 314