OpenApi 3 从外部文件导入模式

OpenApi 3 import schemas from external files

我正在为 Web 服务定义通用模式,我想将它们导入规范的 components/schema 部分。 我想创建一个跨多个服务通用的规范数据模型,以避免在每个服务定义中重新定义相似的对象。

有办法吗? 是否有与 XSD 对其导入标签所做的类似的机制?

您可以 $ref 直接使用绝对或相对 URL 的外部 OpenAPI 架构对象:

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

其中 Pet.yaml 包含,例如:

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

有关详细信息,请参阅 Using $ref

如果 Pet.yaml 不是一个普通对象,而是有几个像这样的对象,为了扩展海伦对那些从 Google 登陆这里的人的回答:

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

你可以这样引用:

$ref: './common/Pet.yaml#/components/schemas/pet'