Request bodies and responses

OpenAPI · Essentials · 12 min

Clients care most about exactly what they send and get back.

A request body is described with requestBody, keyed by media type under content:

requestBody:
  required: true
  content:
    application/json:
      schema: { $ref: '#/components/schemas/NewBook' }

Several media types can be offered (application/json, multipart/form-data, application/x-www-form-urlencoded). Request bodies are optional unless required: true.

Responses are keyed by HTTP status code (quoted strings in YAML: '200'), by range ('4XX'), or default for everything else. Each response must have a description and may have content and headers:

  • Document every status a client should handle: success, 400 validation errors, 401/403, 404, 409, 429.
  • Use default for a shared error format, ideally RFC 9457 Problem Details (application/problem+json).
  • Responses without a body (e.g. 204) simply omit content.
  • Response headers cover things like Location after a 201 or Retry-After on 429.

Examples make docs and mocks realistic. Use example inside a schema, or named examples on a media type (each with summary and value). Mock servers and docs pick them up.

Example

paths:
  /books:
    post:
      operationId: createBook
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title, isbn]
              properties: { title: { type: string }, isbn: { type: string, pattern: '^\d{13}$' } }
            examples:
              novel: { summary: A novel, value: { title: Kindred, isbn: '9780807083697' } }
      responses:
        '201':
          description: Created
          headers:
            Location: { schema: { type: string, format: uri } }
        '400':
          description: Validation failed
          content:
            application/problem+json:
              schema: { type: object, properties: { title: { type: string }, detail: { type: string } } }

Remember

  • Bodies are described per media type under content
  • Responses keyed by status code (quoted), range or default
  • Every response needs a description
  • Named examples feed docs and mock servers

Watch out for

  • Documenting only the 200 response, leaving clients to discover error formats in production.

Check yourself

  1. How do you describe a 204 No Content response?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.openapis.org/specification/content.html