首页 文章

如何在OpenAPI(Swagger)中定义一个可以是字符串或null的属性?

提问于
浏览
17

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

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

转换为YAML(与OpenAPI / Swagger一起使用)时,它变为:

type:
  - 'null'
  - string

但Swagger编辑器显示错误:

Schema“type”键必须是一个字符串

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

1 回答

  • 25

    type 作为一个类型的数组

    type:
      - string
      - 'null'
    

    在OpenAPI / Swagger中是 NOT valid (即使它's valid in JSON Schema). OpenAPI' s type 关键字需要单一类型且不能是类型数组 .

    null 的支持取决于您使用的OpenAPI版本:

    • OpenAPI 3.0 中,使用nullable关键字定义可空类型:
    type: string
    nullable: true   # <----
    
    • OpenAPI 2.0 不支持 null 作为数据类型,因此如果使用2.0,则运气不佳 . 你只能使用 type: string . 也就是说,有些工具支持 x-nullable: true 作为供应商扩展,即使空值不是OpenAPI 2.0规范的一部分 .

相关问题