Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Paths, Schemas and Components

OpenAPI Request Bodies and Media Types (JSON, Forms, Files)

Describe request bodies in OpenAPI: requestBody, content and media types, JSON payloads, form-urlencoded, multipart file uploads, examples and body validation.

When a client creates or changes something, it sends data in the body of the request. OpenAPI 3.x gives that its own object, requestBody, separate from parameters (Swagger 2.0 hid it as a parameter with in: body). The body is described as a map from media type to schema, so one operation can accept several formats.

The requestBody object

YAML
paths:
  /pets:
    post:
      operationId: createPet
      requestBody:
        description: The pet to add
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, minLength: 1 }
                tag:  { type: string }
            example:
              name: Fido
              tag: dog
      responses:
        "201":
          description: Created
  • content is required and maps media types to a media type object.
  • required defaults to false. If a body is mandatory, say required: true.
  • description supports Markdown.
  • A media type object has schema, example or examples, and for forms an encoding map.

Several media types for one operation

YAML
requestBody:
  content:
    application/json:
      schema: { $ref: "#/components/schemas/NewPet" }
    application/xml:
      schema: { $ref: "#/components/schemas/NewPet" }

The server picks the one matching the Content-Type header. Media type keys may use wildcards such as image/* or */*, and a more specific key wins.

Form submissions

HTML-style forms use application/x-www-form-urlencoded:

YAML
requestBody:
  content:
    application/x-www-form-urlencoded:
      schema:
        type: object
        required: [username, password]
        properties:
          username: { type: string }
          password: { type: string, format: password }

A client sends username=ana&password=... encoded in the body.

File uploads with multipart

For files (and mixed data) use multipart/form-data. In 3.1 a file field is described with contentMediaType (in 3.0 you used format: binary):

YAML
requestBody:
  content:
    multipart/form-data:
      schema:
        type: object
        properties:
          caption: { type: string }
          photo:
            type: string
            contentMediaType: image/png      # 3.1
            # format: binary                 # 3.0 equivalent
      encoding:
        photo:
          contentType: image/png, image/jpeg

To send raw binary as the whole body (for example uploading one image), describe a media type whose schema is empty or has contentMediaType:

YAML
requestBody:
  content:
    image/png:
      schema: {}      # 3.1: any bytes

Examples

example is one value; examples is a named map, each with summary, description and value:

YAML
content:
  application/json:
    schema: { $ref: "#/components/schemas/NewPet" }
    examples:
      dog:
        summary: A dog
        value: { name: Rex, tag: dog }
      minimal:
        summary: Only the required field
        value: { name: Mia }

Documentation tools show them in a drop-down, and mock servers return them. Make sure every example validates against its schema, because an example that breaks the contract confuses everyone.

Validate a body against its description

A server (or a gateway, see validation) checks incoming data against the request body schema. This stand-in handles required, property types and unknown fields so you can see how a body is accepted or rejected.

Python Stand-in: validate a JSON request body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

PUT, PATCH and request bodies

  • POST and PUT typically take the full representation of the resource.
  • PATCH takes a partial one. Describe it with a separate schema in which no property is required, or use the JSON Merge Patch media type (application/merge-patch+json) and say so in the description.
YAML
patch:
  requestBody:
    content:
      application/merge-patch+json:
        schema:
          type: object
          properties:
            name: { type: string }
            tag:  { type: [string, "null"] }   # null removes the tag

Never reuse your response schema as the request schema if it contains server-generated fields such as id or createdAt. Either mark them readOnly: true or create a separate request schema (for example NewPet and Pet). Otherwise generated clients force callers to send fields they cannot know.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which field of requestBody is mandatory?

    content is the only required field; required defaults to false.
  2. 2. What is the default of requestBody.required?

    A request body is optional unless you say required: true.
  3. 3. Which media type do you use for a file upload mixed with text fields?

    Multipart form data carries several parts, including files.
  4. 4. Why use separate NewPet and Pet schemas?

    Requests should contain only what the client controls; responses add server fields.

Summary

  • requestBody holds an optional description, a required flag and the mandatory content map.
  • Each media type has its own schema, examples and, for forms, encoding.
  • Use application/x-www-form-urlencoded for simple forms and multipart/form-data for files.
  • Provide valid examples; keep request and response schemas separate when server fields differ.

Next: Responses and status codes