当你的 API 接受多种数据格式、包含条件字段或采用继承模式时,OpenAPI 的模式组合关键字可帮助你记录这些灵活的结构。借助 oneOfanyOfallOf,你可以描述同时处理不同输入类型的 API,或将多个模式组合为完整的数据模型。

oneOf, anyOf, allOf 关键字

对于复杂数据类型,OpenAPI 提供了用于组合架构(schema)的关键字:
  • allOf:合并多个架构(例如合并对象或在基础架构之上扩展)。相当于逻辑运算符 and
  • anyOf:接受与任一给定架构匹配的数据。相当于逻辑运算符 or
  • oneOf:接受与给定架构中且仅有一个匹配的数据。相当于逻辑运算符 exclusive-or(异或)。
Mintlify 对 oneOfanyOf 采取相同处理,因为它们在实际使用 API 时的差异通常不会产生影响。
有关这些关键字的详细规范,请参阅 OpenAPI 文档
当前不支持 not 关键字。

使用 allOf 组合架构

当你使用 allOf 时,Mintlify 会对你的 OpenAPI 文档进行一些预处理,以更易读的方式展示复杂的组合。例如,当你用 allOf 合并两个对象架构时,Mintlify 会将两者的属性合并为一个对象。在利用 OpenAPI 的可复用组件时,这一点尤其有用。
org_with_users:
  allOf:
    - $ref: '#/components/schemas/Org'
    - type: object
      properties:
        users:
          type: array
          description: An array containing all users in the organization
# ...
components:
  schemas:
    Org:
      type: object
      properties:
        id:
          type: string
          description: The ID of the organization
org_with_users
object

使用 oneOfanyOf 提供选项

当你使用 oneOfanyOf 时,选项会显示在带有选项卡的容器中。在每个子模式中指定 title 字段以为选项命名。比如,下面演示了两种不同类型的收货地址:
delivery_address:
  oneOf:
    - title: StreetAddress
      type: object
      properties:
        address_line_1:
          type: string
          description: The street address of the recipient
        # ...
    - title: POBox
      type: object
      properties:
        box_number:
          type: string
          description: The number of the PO Box
        # ...
delivery_address
object
address_line_1
string
收件人住址的街道信息