描述參數
在 OpenAPI 3.0 中,參數定義於作業或路徑的 parameters
區段中。若要描述參數,您需要指定其 name
、位置 (in
)、資料類型 (由 schema
或 content
定義) 和其他屬性,例如 description
或 required
。以下範例:
1paths:2 /users/{userId}:3 get:4 summary: Get a user by ID5 parameters:6 - in: path7 name: userId8 schema:9 type: integer10 required: true11 description: Numeric ID of the user to get
請注意,parameters
是一個陣列,因此,在 YAML 中,每個參數定義前面都必須以破折號 (-
) 列出。
參數類型
OpenAPI 3.0 根據參數位置區分下列參數類型。位置由參數的 in
鍵決定,例如 in: query
或 in: path
。
- 路徑參數,例如
/users/{id}
- 查詢參數,例如
/users?role=admin
- 標頭參數,例如
X-MyHeader: Value
- Cookie 參數,其在
Cookie
標頭中傳遞,例如Cookie: debug=0; csrftoken=BUSe35dohU3O1MZvDCU
路徑參數
路徑參數是 URL 路徑的可變部分。它們通常用於指向集合中的特定資源,例如由 ID 識別的使用者。URL 可以有多個路徑參數,每個參數都以大括號 { }
表示。
1GET /users/{id}2GET /cars/{carId}/drivers/{driverId}3GET /report.{format}
當用戶端發出 API 呼叫時,每個路徑參數都必須替換為實際值。在 OpenAPI 中,路徑參數使用 in: path
定義。參數名稱必須與路徑中指定的名稱相同。另請記得新增 required: true
,因為路徑參數一律為必要。例如,/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 schema:9 type: integer10 minimum: 111 description: The user ID
包含陣列和物件的路徑參數可以使用不同的方式序列化
- 路徑樣式擴充 (矩陣) – 以分號開頭,例如
/map/point;x=50;y=20
- 標籤擴充 – 以點開頭,例如
/color.R=100.G=200.B=150
- 簡單樣式 – 以逗號分隔,例如
/users/12,34,56
序列化方法由 style
和 explode
關鍵字指定。若要深入瞭解,請參閱參數序列化。
查詢參數
查詢參數是最常見的參數類型。它們出現在請求 URL 的結尾,在問號 (?
) 之後,不同的 name=value
配對以 (&) 符號分隔。查詢參數可以是必要和選用。
1GET /pets/findByStatus?status=available2GET /notes?offset=100&limit=50
使用 in: query
表示查詢參數
1parameters:2 - in: query3 name: offset4 schema:5 type: integer6 description: The number of items to skip before starting to collect the result set7 - in: query8 name: limit9 schema:10 type: integer11 description: The numbers of items to return
注意:若要描述以查詢參數形式傳遞的 API 金鑰,請改用 securitySchemes
和 security
。請參閱 API 金鑰。
查詢參數可以是基本值、陣列和物件。OpenAPI 3.0 提供數種方法可以在查詢字串中序列化物件和陣列。
陣列可以序列化為:
form
–/products?color=blue,green,red
或/products?color=blue&color=green
,取決於explode
關鍵字spaceDelimited
(與 OpenAPI 2.0 中的collectionFormat: ssv
相同) –/products?color=blue%20green%20red
pipeDelimited
(與 OpenAPI 2.0 中的collectionFormat: pipes
相同) –/products?color=blue|green|red
物件可以序列化為:
form
–/points?color=R,100,G,200,B,150
或/points?R=100&G=200&B=150
,取決於explode
關鍵字deepObject
–/points?color[R]=100&color[G]=200&color[B]=150
序列化方法由 style
和 explode
關鍵字指定。若要深入瞭解,請參閱參數序列化。
查詢參數中的保留字元
RFC 3986 定義了一組保留字元 :/?#[]@!$&'()*+,;=
,用作 URI 元件分隔符號。當這些字元需要以文字形式在查詢參數值中使用時,它們通常會經過百分比編碼。例如,/
編碼為 %2F
(或 %2f
),以便參數值 quotes/h2g2.txt
會傳送為:
1GET /file?path=quotes%2Fh2g2.txt
如果您想要未經過百分比編碼的查詢參數,請將 allowReserved: true
新增至參數定義:
1parameters:2 - in: query3 name: path4 required: true5 schema:6 type: string7 allowReserved: true # <-----
在此情況下,參數值會像這樣傳送:
1GET /file?path=quotes/h2g2.txt
標頭參數
API 呼叫可能需要將自訂標頭與 HTTP 請求一起傳送。OpenAPI 可讓您將自訂請求標頭定義為 in: header
參數。例如,假設呼叫 GET /ping
需要 X-Request-ID
標頭:
1 GET /ping HTTP/1.12 Host: example.com3 X-Request-ID: 77e1c83b-7bb0-437b-bc50-a7a58e5660ac
使用 OpenAPI 3.0,您會將此作業定義如下:
1paths:2 /ping:3 get:4 summary: Checks if the server is alive5 parameters:6 - in: header7 name: X-Request-ID8 schema:9 type: string10 format: uuid11 required: true
您可以使用類似的方式定義自訂回應標頭。標頭參數可以是基本值、陣列和物件。陣列和物件使用 simple
樣式序列化。如需詳細資訊,請參閱參數序列化。
注意:不允許使用名為 Accept
、Content-Type
和 Authorization
的標頭參數。若要描述這些標頭,請使用對應的 OpenAPI 關鍵字:
標頭 | OpenAPI 關鍵字 | 如需詳細資訊,請參閱... |
---|---|---|
Content-Type |
請求內容類型:requestBody.content.<media-type> 回應內容類型: responses.<code>.content.<media-type> |
描述請求主體, 描述回應, 媒體類型 |
Accept |
responses.<code>.content.<media-type> |
描述回應, 媒體類型 |
Authorization |
securitySchemes 、security |
驗證 |
Cookie 參數
作業也可以在 Cookie
標頭中傳遞參數,如 Cookie: name=value
。多個 Cookie 參數在同一個標頭中傳送,以分號和空格分隔。
1GET /api/users2Host: example.com3Cookie: debug=0; csrftoken=BUSe35dohU3O1MZvDCUOJ
使用 in: cookie
定義 Cookie 參數
1parameters:2 - in: cookie3 name: debug4 schema:5 type: integer6 enum: [0, 1]7 default: 08 - in: cookie9 name: csrftoken10 schema:11 type: string
Cookie 參數可以是原始值、陣列和物件。陣列和物件會使用 form
樣式序列化。如需更多資訊,請參閱參數序列化。
注意:若要定義 Cookie 驗證,請改用API 金鑰。
必要和選用參數
預設情況下,OpenAPI 會將所有請求參數視為選用。您可以加入 required: true
來將參數標記為必要。請注意,路徑參數必須有 required: true
,因為它們永遠是必要的。
1parameters:2 - in: path3 name: userId4 schema:5 type: integer6 required: true # <----------7 description: Numeric ID of the user to get.
schema vs content
若要描述參數內容,您可以使用 schema
或 content
關鍵字。它們是互斥的,並在不同的情況下使用。在大多數情況下,您會使用schema
。它能讓您描述原始值,以及序列化為字串的簡單陣列和物件。陣列和物件參數的序列化方法由該參數中使用的 style
和 explode
關鍵字定義。
1parameters:2 - in: query3 name: color4 schema:5 type: array6 items:7 type: string8
9 # Serialize as color=blue,black,brown (default)10 style: form11 explode: false
content
用於 style
和 explode
無法涵蓋的複雜序列化情境。例如,如果您需要在查詢字串中傳送 JSON 字串,如下所示:
1filter={"type":"t-shirt","color":"blue"}
在這種情況下,您需要將參數 schema
包裝在 content/<media-type>
中,如下所示。 schema
定義參數資料結構,而媒體類型(在此範例中為 application/json
)作為外部規格的參考,用於描述序列化格式。
1parameters:2 - in: query3 name: filter4
5 # Wrap 'schema' into 'content.<media-type>'6 content:7 application/json: # <---- media type indicates how to serialize / deserialize the parameter content8 schema:9 type: object10 properties:11 type:12 type: string13 color:14 type: string
給 Swagger UI 和 Swagger Editor 使用者的注意事項:Swagger UI 3.23.7+ 和 Swagger Editor 3.6.34+ 支援帶有 content
的參數。
預設參數值
使用參數 schema 中的 default
關鍵字來指定選用參數的預設值。預設值是伺服器在用戶端未在請求中提供參數值時使用的值。值類型必須與參數的資料類型相同。典型的範例是諸如 offset
和 limit
之類的分頁參數。
1GET /users2GET /users?offset=30&limit=10
假設 offset
預設為 0,而 limit
預設為 20,範圍從 0 到 100,您將會將這些參數定義為:
1parameters:2 - in: query3 name: offset4 schema:5 type: integer6 minimum: 07 default: 08 required: false9 description: The number of items to skip before starting to collect the result set.10 - in: query11 name: limit12 schema:13 type: integer14 minimum: 115 maximum: 10016 default: 2017 required: false18 description: The number of items to return.
常見錯誤
使用 default
關鍵字時有兩個常見錯誤:
- 將
default
與required
參數或屬性一起使用,例如使用路徑參數。這沒有意義 – 如果一個值是必要的,用戶端必須始終傳送它,並且永遠不會使用預設值。 - 使用
default
來指定範例值。這不是default
的預期用法,並且可能會在某些 Swagger 工具中導致意外的行為。請改用example
或examples
關鍵字來達到此目的。請參閱新增範例。
列舉參數
您可以將參數限制為一組固定值,方法是在參數的 schema
中加入 enum
。列舉值必須與參數資料類型相同。
1parameters:2 - in: query3 name: status4 schema:5 type: string6 enum:7 - available8 - pending9 - sold
更多資訊:定義列舉。
常數參數
您可以將常數參數定義為只有一個可能值的必要參數:
1parameters:2 - in: query3 name: rel_date4 required: true5 schema:6 type: string7 enum:8 - now
enum
屬性指定可能的值。在此範例中,只能使用一個值,而這將會是 Swagger UI 中使用者可選擇的唯一值。
注意:常數參數與預設參數值不同。常數參數始終由用戶端傳送,而預設值是伺服器在用戶端未傳送參數時使用的值。
空值和可為 Null 的參數
查詢字串參數可能只有名稱而沒有值,如下所示:
1GET /foo?metadata
使用 allowEmptyValue
來描述這類參數:
1parameters:2 - in: query3 name: metadata4 schema:5 type: boolean6 allowEmptyValue: true # <-----
OpenAPI 3.0 也支援 schema 中的 nullable
,允許操作參數具有 null
值。例如,以下 schema 對應於 C# 中的 int?
和 Java 中的 java.lang.Integer
:
1schema:2 type: integer3 format: int324 nullable: true
注意:nullable
與選用參數或空值參數不同。 nullable
表示參數值可以為 null
。特定的實作可能會選擇將不存在或空值參數對應到 null
,但嚴格來說,它們不是同一件事。
參數範例
您可以為參數指定一個 example
或多個 examples
。範例值應與參數 schema 相符。單一範例:
1parameters:2 - in: query3 name: limit4 schema:5 type: integer6 minimum: 17 example: 20
多個已命名的範例:
1parameters:2 - in: query3 name: ids4 description: One or more IDs5 required: true6 schema:7 type: array8 items:9 type: integer10 style: form11 explode: false12 examples:13 oneId:14 summary: Example of a single ID15 value: [5] # ?ids=516 multipleIds:17 summary: Example of multiple IDs18 value: [1, 5, 7] # ?ids=1,5,7
如需詳細資訊,請參閱新增範例。
已棄用的參數
使用 deprecated: true
將參數標記為已棄用。
1- in: query2 name: format3 required: true4 schema:5 type: string6 enum: [json, xml, yaml]7 deprecated: true8 description: Deprecated, use the appropriate `Accept` header instead.
通用參數
路徑所有方法通用的參數
路徑所有操作共用的參數可以在路徑層級而非操作層級定義。路徑層級參數會由該路徑的所有操作繼承。典型的使用案例是透過路徑參數存取資源的 GET/PUT/PATCH/DELETE 操作。
1paths:2 /user/{id}:3 parameters:4 - in: path5 name: id6 schema:7 type: integer8 required: true9 description: The user ID10 get:11 summary: Gets a user by ID12 ...13 patch:14 summary: Updates an existing user with the specified ID15 ...16 delete:17 summary: Deletes the user with the specified ID18 ...
在操作層級定義的任何額外參數都會與路徑層級參數一起使用。
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 schema:7 type: integer8 required: true9 description: The user ID.10
11 # GET/users/{id}?metadata=true12 get:13 summary: Gets a user by ID14 # Note we only define the query parameter, because the {id} is defined at the path level.15 parameters:16 - in: query17 name: metadata18 schema:19 type: boolean20 required: false21 description: If true, the endpoint returns only the user metadata.22 responses:23 "200":24 description: OK
特定的路徑層級參數可以在操作層級覆寫,但無法移除。
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 schema:7 type: integer8 required: true9 description: The user ID.10
11 # DELETE /users/{id} - uses a single ID.12 # Reuses the {id} parameter definition from the path level.13 delete:14 summary: Deletes the user with the specified ID.15 responses:16 "204":17 description: User was deleted.18
19 # GET /users/id1,id2,id3 - uses one or more user IDs.20 # Overrides the path-level {id} parameter.21 get:22 summary: Gets one or more users by ID.23 parameters:24 - in: path25 name: id26 required: true27 description: A comma-separated list of user IDs.28 schema:29 type: array30 items:31 type: integer32 minItems: 133 explode: false34 style: simple35 responses:36 "200":37 description: OK
各種路徑通用的參數
不同的 API 路徑可能具有通用的參數,例如分頁參數。您可以在全域 components
區段的 parameters 下定義通用參數,並透過 $ref
在其他地方參考它們。
1components:2 parameters:3 offsetParam: # <-- Arbitrary name for the definition that will be used to refer to it.4 # Not necessarily the same as the parameter name.5 in: query6 name: offset7 required: false8 schema:9 type: integer10 minimum: 011 description: The number of items to skip before starting to collect the result set.12 limitParam:13 in: query14 name: limit15 required: false16 schema:17 type: integer18 minimum: 119 maximum: 5020 default: 2021 description: The numbers of items to return.22
23paths:24 /users:25 get:26 summary: Gets a list of users.27 parameters:28 - $ref: "#/components/parameters/offsetParam"29 - $ref: "#/components/parameters/limitParam"30 responses:31 "200":32 description: OK33 /teams:34 get:35 summary: Gets a list of teams.36 parameters:37 - $ref: "#/components/parameters/offsetParam"38 - $ref: "#/components/parameters/limitParam"39 responses:40 "200":41 description: OK
請注意,在 components
中定義的參數不是套用至所有操作的參數,它們只是可以輕鬆重複使用的全域定義。
參數相依性
OpenAPI 3.0 不支援參數相依性以及互斥參數。在 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 schema:8 type: string9 description: >10 A relative date range for the report, such as `Today` or `LastWeek`.11 For an exact range, use `start_date` and `end_date` instead.12 - name: start_date13 in: query14 schema:15 type: string16 format: date17 description: >18 The start date for the report. Must be used together with `end_date`.19 This parameter is incompatible with `rdate`.20 - name: end_date21 in: query22 schema:23 type: string24 format: date25 description: >26 The end date for the report. Must be used together with `start_date`.27 This parameter is incompatible with `rdate`.28 responses:29 "400":30 description: Either `rdate` or `start_date`+`end_date` are required.