描述请求体
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!