Skip to content

Describing Request Body

The POST, PUT and PATCH requests can have the request body (payload), such as JSON or XML data. In Swagger terms, the request body is called a body parameter. There can be only one body parameter, although the operation may have other parameters (path, query, header).

Note: The payload of the application/x-www-form-urlencoded and multipart/form-data requests is described by using form parameters, not body parameters.

The body parameter is defined in the operation’s parameters section and includes the following:

  • in: body
  • schema that describes the body data type and structure. The data type is usually an object, but can also be a primitive (such as a string or number) or an array.
  • Optional description.
  • The payload name. It is required but ignored (it is used for documentation purposes only).

Object Payload (JSON, etc.)

Many APIs transmit data as an object, such as JSON. schema for an object should specify type: object and properties for that object. For example, the POST /users operation with this JSON body:

1
{
2
"userName": "Trillian",
3
"firstName": "Tricia",
4
"lastName": "McMillan"
5
}

can be described as:

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

Note: The name of the body parameter is ignored. It is used for documentation purposes only. For a more modular style, you can move the schema definitions to the global definitions section and refer to them by using $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

Primitive Body

Want to POST/PUT just a single value? No problem, you can define the body schema type as a primitive, such as a string or number. Raw request:

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 definition:

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!

Did not find what you were looking for? Ask the community
Found a mistake? Let us know