如何在 OpenAPI 中定义枚举映射? [英] How to define enum mapping in OpenAPI?
问题描述
我正在设计一个 API,我想定义一个枚举严重性,它的值可以是低、中或高.在内部 Severity 被存储为一个整数,所以我想分别将它们映射到 2,1 和 0.有没有办法在 OpenAPI 定义中做到这一点?这是目前我对严重性的要求:
I am designing an API and I want to define an enum Severity which can have values LOW, MEDIUM or HIGH. Internally Severity gets stored as an integer so I want to map these to 2,1 and 0 respectively. Is there a way to do this in an OpenAPI definition? This is currently what I have for Severity:
severity:
type: string
enum:
- HIGH
- MEDIUM
- LOW
推荐答案
OpenAPI 3.1
OpenAPI 3.1 使用最新的 JSON Schema,以及推荐方式 注释 JSON 模式中的单个枚举值是使用 oneOf
+const
而不是 enum
.通过这种方式,您可以为枚举值指定自定义名称 (title
) 和描述.
OpenAPI 3.1
OpenAPI 3.1 uses the latest JSON Schema, and the recommended way to annotate individual enum values in JSON Schema is to use oneOf
+const
instead of enum
. This way you can specify both custom names (title
) and descriptions for enum values.
Severity:
type: integer
oneOf:
- title: HIGH
const: 2
description: An urgent problem
- title: MEDIUM
const: 1
- title: LOW
const: 0
description: Can wait forever
OpenAPI 3.0 和 2.0
这些版本无法为枚举值定义自定义名称,但一些工具为此提供了 x-
扩展.例如:
NSwag 支持 x-enumNames
:
Severity:
type: integer
enum: [2, 1, 0]
x-enumNames: [HIGH, MEDIUM, LOW]
openapi-typescript-codegen 支持 x-enum-varnames
:
Severity:
type: integer
enum: [2, 1, 0]
x-enum-varnames: [HIGH, MEDIUM, LOW]
与您的工具供应商联系,看看他们是否有类似的扩展.
Check with your tooling vendors to see if they have a similar extension.
这篇关于如何在 OpenAPI 中定义枚举映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!