跳至內容

描述請求主體

POST、PUT 和 PATCH 請求可以有請求主體 (承載),例如 JSON 或 XML 資料。在 Swagger 中,請求主體稱為主體參數。只能有一個主體參數,儘管操作可能還有其他參數 (路徑、查詢、標頭)。

注意:application/x-www-form-urlencodedmultipart/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
}

可以描述為

1
paths:
2
/users:
3
post:
4
summary: Creates a new user.
5
consumes:
6
- application/json
7
parameters:
8
- in: body
9
name: user
10
description: The user to create.
11
schema:
12
type: object
13
required:
14
- userName
15
properties:
16
userName:
17
type: string
18
firstName:
19
type: string
20
lastName:
21
type: string
22
responses:
23
201:
24
description: Created

注意:會忽略主體參數的名稱。它僅用於文件目的。若要採用更模組化的樣式,您可以將綱要定義移至全域 definitions 區段,並使用 $ref 參照它們

1
paths:
2
/users:
3
post:
4
summary: Creates a new user.
5
consumes:
6
- application/json
7
parameters:
8
- in: body
9
name: user
10
description: The user to create.
11
schema:
12
$ref: "#/definitions/User" # <----------
13
responses:
14
200:
15
description: OK
16
definitions:
17
User: # <----------
18
type: object
19
required:
20
- userName
21
properties:
22
userName:
23
type: string
24
firstName:
25
type: string
26
lastName:
27
type: string

基本主體

想要 POST/PUT 單一值?沒問題,您可以將主體綱要類型定義為基本類型,例如字串或數字。原始請求

1
POST /status HTTP/1.1
2
Host: api.example.com
3
Content-Type: text/plain
4
Content-Length: 42
5
6
Time is an illusion. Lunchtime doubly so.

Swagger 定義

1
paths:
2
/status:
3
post:
4
summary: Updates the status message.
5
consumes:
6
- text/plain # <----------
7
parameters:
8
- in: body
9
name: status
10
required: true
11
schema:
12
type: string # <----------
13
responses:
14
200:
15
description: Success!

找不到您要尋找的內容嗎?向社群提問
發現錯誤?讓我們知道