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

Vai*_*til 29 swagger openapi

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

"type":["string", "null"]
Run Code Online (Sandbox Code Playgroud)

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

type:
  - 'null'
  - string
Run Code Online (Sandbox Code Playgroud)

但Swagger编辑器显示错误:

架构"类型"键必须是字符串

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

Hel*_*len 42

type 作为一个类型的数组

type:
  - string
  - 'null'
Run Code Online (Sandbox Code Playgroud)

不是有效的的OpenAPI /扬鞭(即使它是有效的JSON模式).OpenAPI的type关键字需要单一类型,不能是类型数组.

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

  • OpenAPI 3.0中,使用nullable关键字定义可空类型:

    type: string
    nullable: true   # <----
    
    Run Code Online (Sandbox Code Playgroud)
  • OpenAPI 2.0不支持null数据类型,所以如果你使用2.0,那你就不走运了.你只能使用type: string.也就是说,一些工具支持x-nullable: true作为供应商扩展,即使空值不是OpenAPI 2.0规范的一部分.