我正在设计一个 API,我想定义一个枚举 Severity,其值可以为 LOW、MEDIUM 或 HIGH。在内部,Severity 存储为整数,因此我想将它们分别映射到 2,1 和 0。有没有办法在 OpenAPI 定义中做到这一点?这就是我目前的严重性:
severity:
type: string
enum:
- HIGH
- MEDIUM
- LOW
OpenAPI 3.1 使用最新的 JSON Schema,在 JSON Schema 中注释各个枚举值的推荐方式是使用
oneOf
+const
而不是 enum
。通过这种方式,您可以指定自定义名称 (title
) 和枚举值的描述。
Severity:
type: integer
oneOf:
- title: HIGH
const: 2
description: An urgent problem
- title: MEDIUM
const: 1
- title: LOW
const: 0
description: Can wait forever
这些版本无法为枚举值定义自定义名称,但某些工具为此提供了
x-
扩展。例如:
自动休息支持
x-ms-enum
。
NSwag支持
x-enumNames
:
Severity:
type: integer
enum: [2, 1, 0]
x-enumNames: [HIGH, MEDIUM, LOW]
x-enum-varnames
:
Severity:
type: integer
enum: [2, 1, 0]
x-enum-varnames: [HIGH, MEDIUM, LOW]
咨询您的工具供应商,看看他们是否有类似的扩展。
开放API 3.0
您可以使用描述:
Severity:
type: integer
enum: [2, 1, 0]
description: >
dictionary:
* 2 HIGH
* 1 MEDIUM
* 0 LOW
它不会影响自动代码生成,但会在生成的文档中可见。