openapi - 为什么该对象对 OpenAPI 3.0 中的两种模式都有效?

标签 openapi json-schema-validator

在此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 无效,因为它有一个意外的 key hunts,并且对 Cat 无效因为它有一个意外的键吠声

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

最佳答案

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规范(赖特草案 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

关于openapi - 为什么该对象对 OpenAPI 3.0 中的两种模式都有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49938462/

相关文章:

php - 如何为 swagger-php OpenApi 添加接受应用程序/json header

JSON 架构 - 除了架构中声明的字段之外,实例没有其他字段

java - 如何从 java 加载 JSON 模式文件

Swagger 3 : schema for dictionary of dictionaries

yaml - 如何在 Swagger UI 中隐藏服务器描述?

file-upload - 如何在 NestJS for OpenAPI 中注释采用多部分表单数据的端点

swagger - 如何为 404 页面创建 OpenAPI 部分?

javascript - 如何使用嵌套引用验证 JSON 模式

java - 如何从命令行运行 json-schema-validator

java - 使用 json-schema-validator 评估 JSON 文件模式