为什么这个对象对 OpenAPI 3.0 中的两种模式都有效?

Why is this object valid against both schemas in OpenAPI 3.0?

在此doc中,定义了两个模式:

components:
  schemas:
    Dog:
      type: object
      properties:
        bark:
          type: boolean
        breed:
          type: string
          enum: [Dingo, Husky, Retriever, Shepherd]
    Cat:
      type: object
      properties:
        hunts:
          type: boolean
        age:
          type: integer

然后文档说:

The following JSON object is valid against both schemas

{
  "bark": true,
  "hunts": true,
  "breed": "Husky",
  "age": 3      
}

JSON Schema Validation 规范说:

Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value, the child instance for that name successfully validates against the corresponding schema.

如果我理解正确,这个对象对 Dog 无效,因为它有一个意外的键 hunts,并且对 Cat 无效,因为它有一个意外的键 bark.

为什么文档说这个对象对两种模式都有效?

OpenAPI Schema Object 支持 additionalProperties 关键字,该关键字指定是否允许在实例中使用架构中未明确定义的属性。

在 OpenAPI 3.0 中,默认情况下 additionalProperties = true(与 additionalProperties: {} 相同)。这就是为什么您的示例中的实例对两种模式都有效。

如果您需要禁止额外的属性,请将 additionalProperties: false 显式添加到您的架构中。


I have not found here where this behavior is defined

additionalProperties: true 是默认值,目前没有明确说明,但可以从其他语句中暗示。有一个 PR 明确提到这一点。

OpenAPI 3.0.1 规范说(强调我的):

Schema Object ... is an extended subset of the JSON Schema Specification Wright Draft 00. ... Unless stated otherwise, the property definitions follow the JSON Schema.

和相应的 JSON Schema Validation 规范(Wright Draft 00)说:

If "additionalProperties" is absent, it may be considered present with an empty schema as a value.
...
If "additionalProperties" is an object, validate the value as a schema to all of the properties that weren't validated by "properties" nor "patternProperties".

因此 JSON 架构中的默认值为 additionalProperties: {}。空模式匹配任何实例,这等同于 additionalProperties: true.