继承和多态
模型组合
在您的 API 中,您可能有一些模型模式共享通用属性。您无需为每个模式重复描述这些属性,而是可以将模式描述为通用属性集和特定于模式的属性的组合。在 OpenAPI 版本 3 中,您可以使用 allOf
关键字来执行此操作。
1components:2 schemas:3 BasicErrorModel:4 type: object5 required:6 - message7 - code8 properties:9 message:10 type: string11 code:12 type: integer13 minimum: 10014 maximum: 60015 ExtendedErrorModel:16 allOf: # Combines the BasicErrorModel and the inline model17 - $ref: "#/components/schemas/BasicErrorModel"18 - type: object19 required:20 - rootCause21 properties:22 rootCause:23 type: string
在上面的示例中,ExtendedErrorModel
模式包括其自身的属性和从 BasicErrorModel
继承的属性。注意:在验证数据时,服务器和客户端将针对其组成的每个模型验证组合模型。建议避免使用冲突的属性(例如,具有相同名称但数据类型不同的属性)。
多态
在您的 API 中,您可以有可以使用几种替代模式描述的请求和响应。在 OpenAPI 3.0 中,要描述此类模型,您可以使用 oneOf
或 anyOf
关键字。
1components:2 responses:3 sampleObjectResponse:4 content:5 application/json:6 schema:7 oneOf:8 - $ref: '#/components/schemas/simpleObject'9 - $ref: '#/components/schemas/complexObject'10 …11components:12 schemas:13 simpleObject:14 …15 complexObject:16 …
在此示例中,响应有效负载可以包含 simpleObject
或 complexObject
。
鉴别器
为了帮助 API 使用者检测对象类型,您可以将 discriminator/propertyName
关键字添加到模型定义中。此关键字指向指定数据类型名称的属性。
1components:2 responses:3 sampleObjectResponse:4 content:5 application/json:6 schema:7 oneOf:8 - $ref: '#/components/schemas/simpleObject'9 - $ref: '#/components/schemas/complexObject'10 discriminator:11 propertyName: objectType12 …13 schemas:14 simpleObject:15 type: object16 required:17 - objectType18 properties:19 objectType:20 type: string21 …22 complexObject:23 type: object24 required:25 - objectType26 properties:27 objectType:28 type: string29 …
在我们的示例中,鉴别器指向包含数据类型名称的 objectType
属性。鉴别器仅与 anyOf
或 oneOf
关键字一起使用。重要的是,在 anyOf
或 oneOf
下提到的所有模型都包含鉴别器指定的属性。这意味着,例如,在上面的代码中,simpleObject
和 complexObject
都必须具有 objectType
属性。此属性在这些模式中是必需的。
1schemas:2 simpleObject:3 type: object4 required:5 - objectType6 properties:7 objectType:8 type: string9 …10 complexObject:11 type: object12 required:13 - objectType14 properties:15 objectType:16 type: string17 …
各种 API 使用者可以使用 discriminator
关键字。一个可能的例子是代码生成工具:它们可以使用鉴别器来生成程序语句,这些语句根据鉴别器属性值将请求数据类型转换为适当的对象类型。
映射类型名称
这意味着,鉴别器引用的属性包含目标模式的名称。在上面的示例中,objectType
属性应包含 simpleObject
或 complexObject
字符串。如果属性值与模式名称不匹配,则可以将值映射到名称。为此,请使用 discriminator/mapping
关键字。
1components:2 responses:3 sampleObjectResponse:4 content:5 application/json:6 schema:7 oneOf:8 - $ref: '#/components/schemas/Object1'9 - $ref: '#/components/schemas/Object2'10 - $ref: 'sysObject.json#/sysObject'11 discriminator:12 propertyName: objectType13 mapping:14 obj1: '#/components/schemas/Object1'15 obj2: '#/components/schemas/Object2'16 system: 'sysObject.json#/sysObject'17 …18 schemas:19 Object1:20 type: object21 required:22 - objectType23 properties:24 objectType:25 type: string26 …27 Object2:28 type: object29 required:30 - objectType31 properties:32 objectType:33 type: string34 …
在此示例中,obj1
值映射到同一规范中定义的 Object1
模型,obj2
映射到 Object2
,值 system
与位于外部文件中的 sysObject
模型匹配。所有这些对象都必须具有 objectType
属性,其值分别为 "obj1"
、"obj2"
或 "system"
。