【问题标题】:How to define a property that can be string or null in OpenAPI (Swagger)?如何在 OpenAPI (Swagger) 中定义可以为字符串或 null 的属性?
【发布时间】:2018-06-15 03:20:49
【问题描述】:

我有 JSON 模式文件,其中一个属性定义为 stringnull

"type":["string", "null"]

当转换为 YAML(用于 OpenAPI/Swagger)时,它变为:

type:
  - 'null'
  - string

但 Swagger 编辑器显示错误:

架构“类型”键必须是字符串

在 OpenAPI 中定义可为空的属性的正确方法是什么?

【问题讨论】:

标签: swagger openapi


【解决方案1】:

这取决于 OpenAPI 版本。

OpenAPI 3.1

您的示例在 OpenAPI 3.1 中有效,它与 JSON Schema 2020-12 完全兼容。

type:
  - 'null'   # Note the quotes around 'null'
  - string

# same as
type: ['null', string]

以上等价于:

oneOf:
  - type: 'null'   # Note the quotes around 'null'
  - type: string

OAS 3.0.x 中使用的 nullable 关键字(见下文)在 OAS 3.1 中不存在,它已被删除以支持 'null' 类型。

OpenAPI 3.0.x

可空字符串定义如下:

type: string
nullable: true

这与 JSON Schema 语法不同,因为直到 3.0.x 的 OpenAPI 版本使用自己的 flavor of JSON Schema(“扩展子集”)。区别之一是type 必须是单一类型,不能是类型列表。也没有'null' 类型;相反,nullable 关键字用作type 修饰符以允许null 值。

OpenAPI 2.0

OAS2 不支持 'null' 作为数据类型,所以你运气不好。您只能使用type: string。然而,一些工具支持 x-nullable: true 作为供应商扩展,即使空值不是 OpenAPI 2.0 规范的一部分。

考虑迁移到 OpenAPI v. 3 以获得对空值的适当支持。

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 2018-02-17
    • 2018-12-26
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    相关资源
    最近更新 更多