跳到内容

描述请求正文

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!

没有找到您要找的内容?询问社区
发现错误?告诉我们

© . All rights reserved.