Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Validation and Contract Testing

Validating Requests and Responses Against OpenAPI

Use an OpenAPI document to validate incoming requests and outgoing responses at runtime, learn what to check, where to place validators, and run a stand-in validator.

A spec is a promise. Runtime validation enforces that promise while the API is running: an incoming request is checked against the operation's parameters and body schema, and an outgoing response is checked against the declared response schema. Done well, this gives you automatic 400 and 422 answers for bad input, and an alarm when your own server breaks its contract.

Several libraries do this: express-openapi-validator (Node), openapi-core (Python), committee (Ruby), swagger-request-validator (Java), Prism in proxy mode, and framework features such as FastAPI's built-in validation. None can run on this site, so the stand-in below implements the idea in Python.

What to check

On the request:

  1. Route: does the method and path exist in the spec?
  2. Path, query and header parameters: required ones present, types correct, values in range, enums respected.
  3. Content type: is the Content-Type one of the media types declared in requestBody.content?
  4. Body: does the JSON match the schema (types, required properties, constraints)?
  5. Security: is a credential present for operations that declare security?

On the response:

  1. Is the status code declared (or covered by default)?
  2. Is the content type declared?
  3. Does the body match the schema for that status?
  4. Are required headers present?
flowchart LR
  C["Client"] --> V1["Request validator"]
  V1 -- "invalid" --> E["400 / 422"]
  V1 -- "valid" --> H["Handler"]
  H --> V2["Response validator"]
  V2 -- "invalid" --> L["Log, alert, or 500 in test"]
  V2 -- "valid" --> C

Request validation protects the server; response validation protects clients.

Strictness decisions

Validation involves choices you should make deliberately:

  • additionalProperties: the default is to allow unknown properties. Set additionalProperties: false where you want unknown fields rejected, and know that this makes adding fields a breaking change for strict clients.
  • Coercion: query values arrive as strings. Libraries can coerce "5" to an integer; decide whether you accept that.
  • Response validation in production: it costs CPU and can turn a small mismatch into a failed request. Many teams validate responses in tests and staging, and only log mismatches in production.
  • Error format: return a consistent body (for example application/problem+json) listing each failed field.

A stand-in request validator

The code below validates requests against a small spec: route matching, required and typed query parameters, and a body schema check. It returns a status and a list of problems, like a validation middleware would.

Python Stand-in: validate requests against a spec

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.

A stand-in response checker

The second stand-in does the reverse for responses: it checks that a handler's output uses a declared status and a body of the right shape. This is the check that catches a server leaking a new field, returning null for a required one, or sending 201 where the spec says 200.

Python Stand-in: check responses against the contract

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.

Where to place validators

  • In the app as middleware: simplest, closest to the handlers.
  • At a gateway: several gateways (Kong, Apigee, Azure APIM and others) can validate against an OpenAPI file before traffic reaches your service.
  • In tests only: wrap your HTTP test client so every response in the suite is checked against the spec. This is cheap and catches most drift.

Validation proves shape, not meaning. A response can match its schema and still contain the wrong price. Pair validation with contract tests and ordinary behavior tests.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why is response validation often limited to tests and staging?

    Many teams log mismatches in production but enforce them in tests, where failures are safe and informative.
  2. 2. What effect does additionalProperties: false have on a request body schema?

    It forbids properties not listed in the schema, which also makes adding new fields a breaking change for strict clients.
  3. 3. Which problem is response validation designed to catch?

    It compares what the server actually sends to what the contract promises.

Summary

  • Runtime validation checks routes, parameters, content types and bodies on the request, and status, headers and body on the response.
  • Decide strictness: additionalProperties, coercion, and whether to enforce responses in production.
  • Place validators in middleware, at a gateway or in your test client.
  • Validation proves shape only; add behavior and contract tests.
  • The Python validators here are stand-ins for the library logic.

Next: Mock servers with Prism