描述請求主體
POST、PUT 和 PATCH 請求可以有請求主體 (承載),例如 JSON 或 XML 資料。在 Swagger 中,請求主體稱為主體參數。只能有一個主體參數,儘管操作可能還有其他參數 (路徑、查詢、標頭)。
注意:application/x-www-form-urlencoded
和 multipart/form-data
請求的承載是使用表單參數而非主體參數來描述。
主體參數定義在操作的參數區段中,並包括以下內容
in: body
schema
,描述主體資料類型和結構。資料類型通常是物件,但也可能是基本類型 (例如字串或數字) 或陣列。- 選用的
description
。 - 承載名稱。它是必要的,但會被忽略 (僅用於文件目的)。
物件承載 (JSON 等)
許多 API 以物件 (例如 JSON) 形式傳輸資料。物件的 schema
應指定 type: object
以及該物件的屬性。例如,使用此 JSON 主體的 POST /users
操作
1{2 "userName": "Trillian",3 "firstName": "Tricia",4 "lastName": "McMillan"5}
可以描述為
1paths:2 /users:3 post:4 summary: Creates a new user.5 consumes:6 - application/json7 parameters:8 - in: body9 name: user10 description: The user to create.11 schema:12 type: object13 required:14 - userName15 properties:16 userName:17 type: string18 firstName:19 type: string20 lastName:21 type: string22 responses:23 201:24 description: Created
注意:會忽略主體參數的名稱。它僅用於文件目的。若要採用更模組化的樣式,您可以將綱要定義移至全域 definitions
區段,並使用 $ref
參照它們
1paths:2 /users:3 post:4 summary: Creates a new user.5 consumes:6 - application/json7 parameters:8 - in: body9 name: user10 description: The user to create.11 schema:12 $ref: "#/definitions/User" # <----------13 responses:14 200:15 description: OK16definitions:17 User: # <----------18 type: object19 required:20 - userName21 properties:22 userName:23 type: string24 firstName:25 type: string26 lastName:27 type: string
基本主體
想要 POST/PUT 單一值?沒問題,您可以將主體綱要類型定義為基本類型,例如字串或數字。原始請求
1POST /status HTTP/1.12Host: api.example.com3Content-Type: text/plain4Content-Length: 425
6Time is an illusion. Lunchtime doubly so.
Swagger 定義
1paths:2 /status:3 post:4 summary: Updates the status message.5 consumes:6 - text/plain # <----------7 parameters:8 - in: body9 name: status10 required: true11 schema:12 type: string # <----------13 responses:14 200:15 description: Success!