跳至內容

列舉

您可以使用 enum 關鍵字來指定請求參數或模型屬性的可能值。例如,GET /items?sort=[asc|desc] 中的排序參數可以描述為

1
paths:
2
/items:
3
get:
4
parameters:
5
- in: query
6
name: sort
7
description: Sort order
8
schema:
9
type: string
10
enum: [asc, desc]

在 YAML 中,您也可以每行指定一個列舉值

1
enum:
2
- asc
3
- desc

列舉中的所有值都必須符合指定的 type。如果您需要為列舉項目指定描述,您可以在參數或屬性的 description 中執行此動作

1
parameters:
2
- in: query
3
name: sort
4
schema:
5
type: string
6
enum: [asc, desc]
7
description: >
8
Sort order:
9
* `asc` - Ascending, from A to Z
10
* `desc` - Descending, from Z to A

可為空的列舉

可為空的列舉可以定義如下

1
type: string
2
nullable: true # <---
3
enum:
4
- asc
5
- desc
6
- null # <--- without quotes, i.e. null not "null"

請注意,null 必須明確包含在 enum 值的清單中。單獨使用 nullable: true 是不夠的

可重複使用的列舉

在 OpenAPI 3.0 中,操作參數和資料模型都使用 schema,可以輕鬆重複使用資料類型。您可以在全域 components 區段中定義可重複使用的列舉,並透過 $ref 在其他地方參考它們。

1
paths:
2
/products:
3
get:
4
parameters:
5
- in: query
6
name: color
7
required: true
8
schema:
9
$ref: "#/components/schemas/Color"
10
responses:
11
"200":
12
description: OK
13
components:
14
schemas:
15
Color:
16
type: string
17
enum:
18
- black
19
- white
20
- red
21
- green
22
- blue

找不到您要找的東西嗎? 詢問社群
發現錯誤? 告訴我們