描述參數
在 Swagger 中,API 操作參數定義於操作定義中的 parameters
區段下。每個參數都有 name
、值 type
(用於基本值參數) 或 schema
(用於請求主體),以及選用的 description
。以下是一個範例
1paths:2 /users/{userId}:3 get:4 summary: Gets a user by ID.5 parameters:6 - in: path7 name: userId8 type: integer9 required: true10 description: Numeric ID of the user to get.
請注意,parameters
是一個陣列,因此,在 YAML 中,每個參數定義都必須在前面加上破折號 (-
) 列出。
參數類型
Swagger 會根據參數位置區分以下參數類型。位置由參數的 in
鍵決定,例如,in: query
或 in: path
。
- 查詢參數,例如
/users?role=admin
- 路徑參數,例如
/users/{id}
- 標頭參數,例如
X-MyHeader: Value
- 描述 POST、PUT 和 PATCH 請求主體的 body 參數 (請參閱描述請求主體)
- 表單參數 – 用於描述
Content-Type
為application/x-www-form-urlencoded
和multipart/form-data
的請求酬載的各種 body 參數 (後者通常用於檔案上傳)
查詢參數
查詢參數是最常見的參數類型。它們出現在請求 URL 的結尾,在問號 (?
) 之後,不同的 name=value
配對以 & 符號 (&
) 分隔。查詢參數可以是必要或選用的。
1GET /pets/findByStatus?status=available2GET /notes?offset=100&limit=50
使用 in: query
表示查詢參數
1parameters:2 - in: query3 name: offset4 type: integer5 description: The number of items to skip before starting to collect the result set.6 - in: query7 name: limit8 type: integer9 description: The numbers of items to return.
查詢參數僅支援基本類型。您可以有 array
,但 items
必須是基本值類型。不支援物件。
注意:若要描述作為查詢參數傳遞的 API 金鑰,請改用安全性定義。請參閱API 金鑰。
路徑參數
路徑參數是 URL 路徑中可能會變動的元件。它們通常用於指向集合中的特定資源,例如由 ID 識別的使用者。URL 可以有多個路徑參數,每個參數都以大括號 { }
表示。
1GET /users/{id}2GET /cars/{carId}/drivers/{driverId}
當用戶端發出 API 呼叫時,每個路徑參數都必須替換為實際值。在 Swagger 中,路徑參數是使用 in: path
和其他必要屬性定義的。參數名稱必須與路徑中指定的名稱相同。此外,請記住新增 required: true
,因為路徑參數始終是必要的。以下是 GET /users/{id}
的範例
1paths:2 /users/{id}:3 get:4 parameters:5 - in: path6 name: id # Note the name is the same as in the path7 required: true8 type: integer9 minimum: 110 description: The user ID.11 responses:12 200:13 description: OK
路徑參數可以是多值的,例如 GET /users/12,34,56
。這是透過將參數類型指定為 array
來實現的。請參閱下方的陣列和多值參數。
標頭參數
API 呼叫可能需要隨 HTTP 請求傳送自訂標頭。Swagger 可讓您將自訂請求標頭定義為 in: header
參數。例如,假設呼叫 GET /ping
需要 X-Request-ID
標頭
1GET /ping HTTP/1.12Host: example.com3X-Request-ID: 77e1c83b-7bb0-437b-bc50-a7a58e5660ac
在 Swagger 中,您會將此操作定義如下
1paths:2 /ping:3 get:4 summary: Checks if the server is alive.5 parameters:6 - in: header7 name: X-Request-ID8 type: string9 required: true
以類似的方式,您可以定義自訂回應標頭。
注意:Swagger 規格對於某些標頭有特殊的關鍵字
標頭 | Swagger 關鍵字 | 如需更多資訊,請參閱... |
---|---|---|
Content-Type |
consumes (請求內容類型)produces (回應內容類型) |
MIME 類型 |
Accept |
produces |
MIME 類型 |
Authorization |
securityDefinitions 、security |
驗證 |
表單參數
表單參數用於描述 Content-Type
為的請求酬載
application/x-www-form-urlencoded
(用於 POST 基本值和基本值陣列)。multipart/form-data
(用於上傳檔案或檔案與基本資料的組合)。
也就是說,操作的 consumes
屬性必須指定其中一種內容類型。表單參數定義為 in: formData
。它們只能是基本類型 (字串、數字、布林值) 或基本類型陣列 (表示您不能使用 $ref
作為 items
值)。此外,表單參數不能與 in: body
參數共存,因為 formData
是一種描述主體的特定方式。為了說明表單參數,請考慮一個 HTML POST 表單
1<form action="http://example.com/survey" method="post">2 <input type="text" name="name" />3 <input type="number" name="fav_number" />4 <input type="submit" />5</form>
此表單會將資料 POST 到表單的端點。
1POST /survey HTTP/1.12Host: example.com3Content-Type: application/x-www-form-urlencoded4Content-Length: 295
6name=Amy+Smith&fav_number=321
在 Swagger 中,您可以如下描述端點:
1paths:2 /survey:3 post:4 summary: A sample survey.5 consumes:6 - application/x-www-form-urlencoded7 parameters:8 - in: formData9 name: name10 type: string11 description: A person's name.12 - in: formData13 name: fav_number14 type: number15 description: A person's favorite number.16 responses:17 200:18 description: OK
若要了解如何為檔案上傳定義表單參數,請參閱檔案上傳。
必要和選用參數
預設情況下,Swagger 會將所有請求參數視為可選。您可以新增 required: true
來將參數標記為必要。請注意,路徑參數必須具有 required: true
,因為它們始終是必要的。
1parameters:2 - in: path3 name: userId4 type: integer5 required: true # <----------6 description: Numeric ID of the user to get.
預設參數值
您可以使用 default
鍵來為可選參數指定預設值。如果用戶端在請求中沒有提供參數值,伺服器會使用預設值。數值類型必須與參數的資料類型相同。典型的範例是分頁參數,例如 offset 和 limit。
1GET /users2GET /users?offset=30&limit=10
假設 offset 預設為 0,而 limit 預設為 20,且範圍為 0 到 100,您會將這些參數定義為:
1parameters:2 - in: query3 name: offset4 type: integer5 required: false6 default: 07 minimum: 08 description: The number of items to skip before starting to collect the result set.9 - in: query10 name: limit11 type: integer12 required: false13 default: 2014 minimum: 115 maximum: 10016 description: The numbers of items to return.
常見錯誤
使用 default
關鍵字時有兩個常見錯誤:
- 將
default
與required
參數或屬性一起使用,例如,與路徑參數一起使用。這是沒有意義的,如果一個值是必要的,用戶端必須始終發送它,而預設值永遠不會被使用。 - 使用
default
來指定範例值。這並非 default 的預期用法,並可能導致某些 Swagger 工具中出現非預期的行為。規格的某些元素支援使用example
或examples
關鍵字來達到此目的。
列舉參數
enum
關鍵字允許您將參數值限制為一組固定的值。enum 值必須與參數的 type
類型相同。
1- in: query2 name: status3 type: string4 enum: [available, pending, sold]
更多資訊:定義 Enum。
陣列和多值參數
路徑、查詢、標頭和表單參數可以接受一個數值列表,例如:
1GET /users/12,34,56,782GET /resource?param=value1,value2,value33GET /resource?param=value1¶m=value2¶m=value34
5POST /resource6param=value1¶m=value2
必須使用 type: array
和適當的 collectionFormat
來定義多值參數。
1# color=red,black,white2parameters:3 - in: query4 name: color5 type: array6 collectionFormat: csv7 items:8 type: string
collectionFormat
指定陣列格式(具有多個參數的單一參數或具有相同名稱的多個參數)以及陣列項目的分隔符。
collectionFormat | 描述 | 範例 |
---|---|---|
csv (預設) |
逗號分隔值。 | foo,bar,baz |
ssv |
空格分隔值。 | foo bar baz |
tsv |
Tab 分隔值。 | "foo\tbar\tbaz" |
pipes |
管道符號分隔值。 | foo|bar|baz |
multi |
多個參數實例,而不是多個值。這僅支援用於 in: query 和 in: formData 參數。 |
foo=value&foo=another_value |
此外,您可以
- 使用
minItems
和maxItems
來控制陣列的大小, - 強制執行
uniqueItems
, - 將陣列項目限制為一組固定的
enum
值。
例如:
1- in: query2 name: color3 required: false4 type: array5 minItems: 16 maxItems: 57 uniqueItems: true8 items:9 type: string10 enum:11 [12 black,13 white,14 gray,15 red,16 pink,17 orange,18 yellow,19 green,20 blue,21 purple,22 brown,23 ]
您也可以指定如果省略此參數,伺服器將使用的預設陣列。
1- in: query2 name: sort3 required: false4 type: array5 items:6 type: string7 default: ["-modified", "+id"]
常數參數
您可以將常數參數定義為只有一個可能值的必要參數。
1- required: true2 enum: [value]
enum
屬性指定可能的值。在此範例中,只能使用一個值,而這將是 Swagger UI 中供使用者選擇的唯一值。
注意: 常數參數與預設參數值不同。常數參數始終由用戶端發送,而預設值是如果用戶端未發送參數,伺服器會使用的值。
沒有值的參數
查詢字串和表單資料參數可能只有名稱而沒有值。
1GET /foo?metadata2
3POST /something4foo&bar&baz
使用 allowEmptyValue
來描述此類參數。
1- in: query2 name: metadata3 required: true4 type: boolean5 allowEmptyValue: true # <-----
常用參數
路徑的所有方法之通用參數
可以在路徑本身下定義參數,在這種情況下,參數存在於此路徑下描述的所有操作中。一個典型的範例是操作透過路徑參數存取的相同資源的 GET/PUT/PATCH/DELETE 操作。
1paths:2 /user/{id}:3 parameters:4 - in: path5 name: id6 type: integer7 required: true8 description: The user ID.9
10 get:11 summary: Gets a user by ID.12 ...13 patch:14 summary: Updates an existing user with the specified ID.15 ...16 delete:17 summary: Deletes the user with the specified ID.18 ...
在操作層級定義的任何額外參數都會與路徑層級的參數一起使用。
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 type: integer7 required: true8 description: The user ID.9
10 # GET/users/{id}?metadata=true11 get:12 summary: Gets a user by ID.13 # Note we only define the query parameter, because the {id} is defined at the path level.14 parameters:15 - in: query16 name: metadata17 type: boolean18 required: false19 description: If true, the endpoint returns only the user metadata.20 responses:21 200:22 description: OK
可以在操作層級覆寫特定的路徑層級參數,但無法移除它們。
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 type: integer7 required: true8 description: The user ID.9
10 # DELETE /users/{id} - uses a single ID.11 # Reuses the {id} parameter definition from the path level.12 delete:13 summary: Deletes the user with the specified ID.14 responses:15 204:16 description: User was deleted.17
18 # GET /users/id1,id2,id3 - uses one or more user IDs.19 # Overrides the path-level {id} parameter.20 get:21 summary: Gets one or more users by ID.22 parameters:23 - in: path24 name: id25 required: true26 description: A comma-separated list of user IDs.27 type: array28 items:29 type: integer30 collectionFormat: csv31 minItems: 132 responses:33 200:34 description: OK
不同路徑中的通用參數
不同的 API 路徑可能有一些通用參數,例如分頁參數。您可以在全域 parameters
區段中定義通用參數,並透過 $ref
在個別操作中引用它們。
1parameters:2 offsetParam: # <-- Arbitrary name for the definition that will be used to refer to it.3 # Not necessarily the same as the parameter name.4 in: query5 name: offset6 required: false7 type: integer8 minimum: 09 description: The number of items to skip before starting to collect the result set.10 limitParam:11 in: query12 name: limit13 required: false14 type: integer15 minimum: 116 maximum: 5017 default: 2018 description: The numbers of items to return.19paths:20 /users:21 get:22 summary: Gets a list of users.23 parameters:24 - $ref: "#/parameters/offsetParam"25 - $ref: "#/parameters/limitParam"26 responses:27 200:28 description: OK29 /teams:30 get:31 summary: Gets a list of teams.32 parameters:33 - $ref: "#/parameters/offsetParam"34 - $ref: "#/parameters/limitParam"35 responses:36 200:37 description: OK
請注意,全域 parameters
不是應用於所有操作的參數,它們只是可以輕鬆重複使用的全域定義。
參數相依性
Swagger 不支援參數相依性和互斥參數。在 https://github.com/OAI/OpenAPI-Specification/issues/256 有一個開放的功能請求。您可以做的是在參數描述中記錄限制,並在 400 Bad Request 回應中定義邏輯。例如,考慮接受相對日期範圍 (rdate
) 或精確範圍 (start_date
+ end_date
) 的 /report
端點。
1GET /report?rdate=Today2GET /report?start_date=2016-11-15&end_date=2016-11-20
您可以如下描述此端點:
1paths:2 /report:3 get:4 parameters:5 - name: rdate6 in: query7 type: string8 description: >9 A relative date range for the report, such as `Today` or `LastWeek`.10 For an exact range, use `start_date` and `end_date` instead.11 - name: start_date12 in: query13 type: string14 format: date15 description: >16 The start date for the report. Must be used together with `end_date`.17 This parameter is incompatible with `rdate`.18 - name: end_date19 in: query20 type: string21 format: date22 description: >23 The end date for the report. Must be used together with `start_date`.24 This parameter is incompatible with `rdate`.25 responses:26 400:27 description: Either `rdate` or `start_date`+`end_date` are required.
常見問題
我應該何時使用「type」與「schema」?
schema 僅用於 in: body
參數。任何其他參數都期望一個原始類型,例如 type: string
,或原始類型的 array
。
我可以使用物件作為查詢參數嗎?
這在OpenAPI 3.0中是可行的,但在 2.0 中則否。