跳到内容

描述请求体

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!

没有找到您要找的内容?向社区提问
发现错误?请告知我们