API Schema Validation: What It Is, How to Do It, Tools
API schema validation checks API requests and responses against the schema in your OpenAPI or JSON Schema contract: required fields, types, formats, enums and status codes. You run it in tests (Ajv, REST Assured, Postman), in CI against a running build, and at the gateway (AWS, Azure APIM, Cloudflare) to reject malformed requests.
Reviewed by Sushant Joshi
Part of the OpenAPI, Contract & Schema Testing hub. Start with the pillar guides: OpenAPI testing: how to test an API from its spec · API contract testing: what it is and how it works.
API schema validation is the practice of checking API messages against the schema in the API's contract. On the way in, a validator checks that path and query parameters, headers and the request body match what the OpenAPI document declares. On the way out, it checks that the status code is documented and that the response body has every required field, with the declared types, formats and enum values. It is the mechanism underneath schema-first API contract testing: the contract says what correct looks like, and schema validation proves each request and response matches it.
You can run schema validation in three places, and most teams use at least two: in tests (a validator inside your API test suite), in CI (a spec-driven runner or validating proxy against the build), and at the gateway (AWS API Gateway, Azure API Management, Cloudflare API Shield and others rejecting malformed requests before they reach the service). This guide covers each, with code, then the tools, and finally schema drift: what happens when the implementation and the spec quietly stop agreeing.
In this guide
- What is API schema validation?
- What schema validation checks
- How to do API schema validation in tests
- Schema validation in CI and at the API gateway (with a complete GitHub Actions job)
- API schema validation tools
- Schema drift: when the API and the spec disagree
- Best practices and common pitfalls
- API schema validation FAQ
What is API schema validation?
An API schema is the machine-readable description of what an API accepts and returns. For REST APIs it lives in an OpenAPI document: each operation lists its parameters, its request body schema and a response schema per status code. Those body schemas are written in JSON Schema (OpenAPI 3.1 uses JSON Schema 2020-12 directly; OpenAPI 3.0 uses an extended subset of an older draft).
Schema validation in API testing means taking a real message, a request your test sends or a response it receives, and checking it against that description. It is structural: it does not know whether a user's email is the right email, only that email is present, is a string and looks like an email address.
Here is a small API schema example for GET /users/{id}:
paths:
/users/{id}:
get:
parameters:
- { name: id, in: path, required: true, schema: { type: string, format: uuid } }
responses:
'200':
description: The user
content:
application/json:
schema: { $ref: '#/components/schemas/User' }
'404':
description: No such user
components:
schemas:
User:
type: object
required: [id, email, role]
properties:
id: { type: string, format: uuid }
email: { type: string, format: email }
role: { type: string, enum: [admin, member, viewer] }
age: { type: integer, minimum: 0 }
A response of {"id": "…", "email": "ana@example.com", "role": "owner", "age": "42"} fails validation twice: role is not one of the declared enum values, and age is a string, not an integer. An assertion like expect(body.email).toBe('ana@example.com') would pass on the same response. That is the point of schema validation: one check covers every field the schema describes, including the ones no test author thought to assert.
Schema validation vs contract testing. Schema validation is the mechanism; contract testing is the practice built on it, which adds versioning, breaking-change review and, in consumer-driven setups, each consumer's own expectations. The pillar guide to API contract testing covers that wider practice.
A note on JSON Schema itself. The keywords that do the work (type, required, enum, format, $ref, additionalProperties, oneOf) and the differences between drafts are a topic of their own, covered in our dedicated JSON Schema validation guide. This post stays at the API level: where to validate, against which part of the contract, and with which tools.
What schema validation checks
The purpose of schema validation in API testing is to catch structural breakage early and everywhere at once. A complete validator checks:
| Check | Request side | Response side |
|---|---|---|
| Status code | n/a | Is it one the operation documents? |
| Content type | Does Content-Type match a declared media type? | Does the response media type match? |
| Parameters | Path, query, header and cookie parameters: presence, type, format, enum | n/a |
| Body: required fields | Are required properties present? | Are required properties present? |
| Body: types and formats | string, integer, boolean, array, object; date-time, uuid, email, uri | Same |
| Body: constraints | minimum/maximum, minLength/maxLength, pattern, enum | Same |
| Nullability | nullable: true (3.0) or type: [string, "null"] (3.1) | Same |
| Unknown fields | Rejected only where additionalProperties: false | Same |
| Headers | Required request headers | Documented response headers such as Location |
API response schema validation is where most drift shows up, because responses change when the implementation changes. Request validation matters most at the edge: it stops malformed or hostile input before it reaches business logic, which is why gateways implement it. In tests you want both: validate the requests your negative tests send are wrong in exactly the way you intended, and validate every response.
How to do API schema validation in tests
The pattern is the same in every language: load the schema for the operation and status code from the OpenAPI file (never a hand-copied duplicate), call the endpoint, validate the body, and fail with the validator's error path.
JavaScript or TypeScript with Ajv
// user.schema.test.js
import Ajv2020 from 'ajv/dist/2020.js'; // OpenAPI 3.1 = JSON Schema 2020-12
import addFormats from 'ajv-formats';
import yaml from 'js-yaml';
import { readFileSync } from 'node:fs';
const spec = yaml.load(readFileSync('openapi.yaml', 'utf8'));
const ajv = addFormats(new Ajv2020({ allErrors: true, strict: false }));
ajv.addSchema(spec, 'openapi.yaml');
const validateUser = ajv.getSchema('openapi.yaml#/components/schemas/User');
test('GET /users/{id} returns a valid User', async () => {
const res = await fetch(`${process.env.API_URL}/users/${process.env.USER_ID}`);
expect(res.status).toBe(200);
const body = await res.json();
if (!validateUser(body)) throw new Error(ajv.errorsText(validateUser.errors));
});
Registering the whole spec with addSchema lets $ref pointers inside User resolve. For an OpenAPI 3.0 spec, use the default Ajv class (draft-07). Ajv understands OpenAPI's nullable: true out of the box, with one trap: nullable does not extend an enum, so a nullable enum must list null among its values or a null response fails. Two other 3.0 habits need care: exclusiveMinimum/exclusiveMaximum written as booleans (draft-04 style) are numbers in draft-07, and discriminator is only honoured if you construct Ajv with discriminator: true.
Playwright API tests
Playwright has no built-in schema assertion, so the usual approach is the same Ajv validator inside a request test:
import { test, expect } from '@playwright/test';
import { validateUser, ajv } from './schemas'; // compiled as above
test('user endpoint matches the schema', async ({ request }) => {
const res = await request.get(`/users/${process.env.USER_ID}`);
expect(res.status()).toBe(200);
const body = await res.json();
expect(validateUser(body), ajv.errorsText(validateUser.errors)).toBe(true);
});
Java with REST Assured
REST Assured's json-schema-validator module validates a body against a JSON Schema file on the classpath:
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
@Test
void userMatchesSchema() {
given().pathParam("id", userId)
.when().get("/users/{id}")
.then().statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/user.json"));
}
That module validates against a standalone JSON Schema file. To validate against the OpenAPI document itself, including parameters and status codes, the Atlassian swagger-request-validator-restassured filter (OpenApiValidationFilter) checks each request and response a REST Assured test makes against the spec.
Score your OpenAPI spec (free)
Free, runs in your browser, no sign-up needed.
Python with openapi-core
from openapi_core import OpenAPI
from openapi_core.contrib.requests import RequestsOpenAPIRequest, RequestsOpenAPIResponse
import requests
openapi = OpenAPI.from_file_path("openapi.yaml")
def test_get_user_matches_spec(api_url, user_id):
resp = requests.get(f"{api_url}/users/{user_id}")
openapi.validate_response(
RequestsOpenAPIRequest(resp.request), RequestsOpenAPIResponse(resp)
) # raises with the failing path on any mismatch
openapi-core validates against the operation in the spec, so it checks the status code and content type as well as the body. Frameworks such as FastAPI validate requests with Pydantic models at runtime and publish an OpenAPI document generated from them; validating responses against that published document in tests catches handlers that return something other than what the document says.
Postman
Schema validation in API testing with Postman uses the built-in jsonSchema assertion, which runs Ajv inside the sandbox:
const userSchema = pm.collectionVariables.get('userSchema'); // stored JSON Schema
pm.test('response matches the User schema', () => {
pm.response.to.have.status(200);
pm.response.to.have.jsonSchema(JSON.parse(userSchema));
});
Older collections use tv4.validate(); it still runs but is deprecated in favour of jsonSchema. Keep the schema in one variable fed from the OpenAPI file rather than pasted into each test, or the copies drift from the spec. Run the collection in CI with Newman or the Postman CLI.
Schema validation in CI and at the API gateway
In CI: spec-driven runners and validating proxies
Test-level validators only check the endpoints someone wrote a test for. Two kinds of CI tooling cover the rest of the spec:
- Spec-driven runners read the OpenAPI document and exercise every operation. Schemathesis generates many inputs per operation with property-based testing and checks, among other things, that each response conforms to the documented schema and status codes. Dredd replays the examples in the spec and checks responses against them.
- Validating proxies sit between your existing tests and the service. Prism in proxy mode forwards each request to the real API and reports any request or response that violates the OpenAPI document, so an existing functional suite gains schema validation without changing a test.
schemathesis run openapi.yaml --url "$API_URL" --checks all
prism proxy openapi.yaml "$API_URL" --errors
A complete CI job
Put the two halves of schema validation side by side in one workflow: a spec diff that catches spec-side drift (someone edited the contract in a way that breaks consumers) and a spec-driven run against the build that catches implementation-side drift (the code no longer returns what the contract says). In GitHub Actions:
# .github/workflows/schema-validation.yml
name: schema-validation
on: pull_request
jobs:
spec-diff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- run: git show origin/${{ github.base_ref }}:openapi.yaml > base.yaml
- uses: oasdiff/oasdiff-action/breaking@v0
with:
base: base.yaml
revision: openapi.yaml
fail-on: ERR
response-validation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: docker compose up -d --wait # start the API under test
- uses: schemathesis/action@v3
with:
schema: openapi.yaml
base-url: http://localhost:8080
checks: all
args: "--report=junit"
Mark both jobs as required checks on main. On an API that has never been validated, start with the spec-diff job only, reconcile the spec with what the service really returns, and then add response-validation; otherwise the first run fails on years of accumulated drift and the job gets switched off.
At the API gateway
Gateway validation protects production, not your test suite: it rejects bad requests at the edge with a 400, before they cost compute or reach code that trusts its input. Most gateways validate requests only, so they complement rather than replace response validation in tests.
- AWS API Gateway (REST APIs). A request validator checks required request parameters and validates the request body against a model, which is a JSON Schema (draft 4). You attach validators per method, or import them from OpenAPI with the
x-amazon-apigateway-request-validatorsextension. Failing requests get a400without invoking the integration. HTTP APIs do not offer this feature. - Azure API Management. The
validate-contentpolicy validates the size and content of request or response bodies against the API's schemas (JSON or XML), with companionvalidate-parameters,validate-headersandvalidate-status-codepolicies. Each can be set toprevent(block),detect(log only) orignore, which makes it practical to start in detect mode on an existing API. - Cloudflare API Shield. Schema validation lets you upload an OpenAPI v3 document and checks incoming requests against it (path, method, parameters and body), then logs or blocks the ones that do not match. It validates requests, not responses.
- Others. WSO2 API Manager can validate request and response payloads against the API's OpenAPI definition when schema validation is enabled for the API, and Kong offers OpenAPI validation through a plugin.
A practical split: gateway request validation for every public endpoint, response validation in tests and CI, and the same OpenAPI file feeding both so there is one source of truth.
API schema validation tools
| Tool | What it validates | Where it runs | Notes |
|---|---|---|---|
| Ajv | Any JSON value against JSON Schema (draft-07, 2019-09, 2020-12) | Node.js tests, browsers | Fast, compiled validators; add ajv-formats for formats |
| openapi-core | Requests and responses against OpenAPI 3.0/3.1 | Python tests and middleware | Checks status codes and media types, not only bodies |
| REST Assured json-schema-validator | Response body against a JSON Schema file | Java tests | Pair with Atlassian swagger-request-validator for full OpenAPI checks |
| Atlassian swagger-request-validator | Requests and responses against OpenAPI | Java (REST Assured, MockMvc, WireMock) | Validates against the spec, not a copied schema |
Postman jsonSchema | Response body against JSON Schema | Postman, Newman, Postman CLI | tv4 is the deprecated predecessor |
| express-openapi-validator | Requests and optionally responses | Node.js Express middleware | Validation inside the service itself |
| Schemathesis | Responses for generated inputs across the whole spec | CLI, pytest, CI | Property-based; finds crashes as well as schema violations |
| Prism | Requests and responses passing through a proxy | CLI, CI | Also serves mocks from the spec |
| Dredd | Responses against spec examples | CLI, CI | Example-driven; repository archived (read-only since November 2024), so prefer Schemathesis or Prism for new work |
| Gateways (AWS, Azure APIM, Cloudflare, WSO2, Kong) | Mainly incoming requests | Production edge | Blocks bad input; response validation varies by gateway |
Where Shift-Left API fits. Shift-Left API, a spec-driven testing platform, imports your OpenAPI or Swagger document and generates tests whose assertions include field and type checks derived from each response schema. It does not have a dedicated JSON-Schema assertion type that validates a whole body against a schema document; instead, passing runs are examined for responses that no longer match the documented contract (a missing required field, a changed primitive type, an undeclared enum value), and re-importing a changed spec shows a breaking or non-breaking diff for review. See OpenAPI test automation. If you need full JSON Schema validation of every body, keep a validator like Ajv or openapi-core in your code-based suite alongside it.
OpenAPI to Test Generation Template Pack
Go from OpenAPI spec to full test coverage. Includes sample specs, example generated tests, edge case patterns, and CI/CD integration guides.
For the contract-testing side of the toolbox (Pact, Spring Cloud Contract, Specmatic, Microcks and diff tools), see contract testing tools compared.
Schema drift: when the API and the spec disagree
Schema drift is what happens when the running API and its documented schema stop agreeing, and nothing notices. A developer renames user_id to userId in a response model, the handler and its unit tests are updated, the OpenAPI file is not, and weeks later a client that reads user_id breaks. Drift goes the other way too: the spec is edited and the code never catches up.
The six common forms:
- Type changes. An integer becomes a string, or an array becomes a single object. Typed clients fail to deserialize.
- Required-field changes. A required field disappears, or a field the spec calls optional becomes one the client depends on.
- Removed or renamed fields. The most immediately destructive: the client reads
undefined. - Format changes. Same type, different shape: ISO 8601 dates become Unix timestamps, integer IDs become UUID strings. Type checks pass;
formatchecks catch it. - Nullable transitions. A field that was never
nullstarts returningnullfor some data states. It appears intermittently, so it is hard to reproduce. - Nested restructuring.
data.user.namebecomesuser_name. Semantically the same, structurally broken.
How to catch it. Response validation on every pull request catches implementation-side drift at the commit that introduces it. Spec-side drift is caught by diffing the spec against main and classifying the change:
git show origin/main:openapi.yaml > /tmp/base.yaml
oasdiff breaking --fail-on ERR /tmp/base.yaml openapi.yaml
Two other habits close the gap. Run a validating proxy or spec-driven runner against staging so drift that slipped through a pull request is still found before release. And on a legacy API, expect the first validation run to fail widely: reconcile the spec with reality once (update the spec to describe what the API really returns, then decide which differences are bugs), and only then make validation build-blocking.
In Shift-Left API the spec side is handled at import: re-importing a changed spec diffs it against the project's current endpoints, flags breaking changes such as a new required parameter, a removed success response or a narrowed enum, and waits for Approve & Import or Reject. Approving creates new endpoint versions; existing tests are not edited. Its API change detection page has the details, and OpenAPI change impact analysis covers what to check before you approve a change.
Best practices and common pitfalls
- Validate against the spec, not a copy. Load schemas from the OpenAPI file in every test. A schema pasted into a test is a second contract that drifts on its own.
- Validate error responses too. Most specs document only
200. Document400,401,403,404,409,422and500bodies (RFC 9457 problem details is a good default) and validate them like any other response. - Get nullability right for your OpenAPI version. OpenAPI 3.0 uses
nullable: true; 3.1 usestype: [string, "null"]. A 3.1 validator ignoresnullable, which produces false failures or, worse, false passes. See OpenAPI 3.1 vs 3.0 for testing. - Decide deliberately on
additionalProperties.falseon response schemas catches accidental data leaks and undocumented fields, but turns every new field into a failure for strict validators. Many teams use it in tests and keep clients tolerant. - Turn on format validation explicitly. Ajv ignores
formatunless you addajv-formats; other validators differ too. Check thatemail,uuidanddate-timeare actually enforced. - Prove the validator can fail. Before trusting a green run, feed it one deliberately wrong response (a string where the spec says integer, a missing required field). A validator that was never seen to fail may be checking an empty schema because a
$refdid not resolve. - Model optional fields correctly. If a field is sometimes absent, leave it out of
required; if it is sometimesnull, make it nullable. Most "flaky schema validation" is a spec that does not describe the real API. - Make failures build-blocking, after a baseline. Reconcile first, then fail the pull request on any schema violation. Validation that only warns is ignored within a sprint.
- Lint the spec. A Spectral ruleset that requires response schemas, examples and
requiredarrays makes every downstream validator more useful. - Use gateway validation for requests, tests for responses. Gateways protect production from bad input; they do not tell you your API returns the wrong shape.
Related reading: Pact Contract Testing: A Hands-On Tutorial With CI
For the end-to-end workflow, from linting the spec to gating CI, see OpenAPI testing: how to test an API from its spec.
API schema validation FAQ
What is schema validation in API testing?
Schema validation in API testing means checking every request a test sends and every response it receives against the schema the API's contract declares, usually an OpenAPI document. The validator confirms required fields are present, values have the declared types and formats, enums only use declared values, and the status code is one the operation documents. It catches structural breakage that value-level assertions miss.
What is an example of API schema validation?
An OpenAPI schema says GET /users/{id} returns an object with a required string id, a required email in email format and an optional integer age. A test calls the endpoint and passes the body to a validator such as Ajv. If the API returns age as the string "42" or omits email, validation fails with the exact path and rule that broke.
How do you validate an API response schema?
Load the response schema for the operation and status code from your OpenAPI file, compile it with a validator (Ajv in JavaScript, openapi-core in Python, REST Assured's json-schema-validator or the Atlassian swagger-request-validator in Java), call the endpoint, and validate the parsed body. Fail the test on any error and print the validator's error path. Run it in CI on every pull request.
How do you do schema validation in API testing with Postman?
In a request's test script, define or load a JSON Schema and assert pm.response.to.have.jsonSchema(schema), which validates the body with Ajv inside Postman's sandbox. Keep the schema in a collection or environment variable, or fetch it from your spec, so it does not drift from the OpenAPI file. Run the collection with Newman or the Postman CLI in CI.
What is REST API schema validation?
REST API schema validation is schema validation applied to HTTP endpoints described by OpenAPI: path, query and header parameters and request bodies are checked on the way in, and status codes, headers and response bodies on the way out. It can run as middleware in the service, in tests, in a validating proxy such as Prism, or at an API gateway.
Does API gateway schema validation replace validation in tests?
No. Gateways such as Amazon API Gateway and Cloudflare API Shield validate incoming requests and reject malformed ones with a 400, which protects production. They do not tell you that your own service returns the wrong response shape, so response validation still belongs in your tests and CI, fed by the same OpenAPI file.
Is API schema validation the same as contract testing?
No. Schema validation is the mechanism: comparing a message with a schema. Contract testing is the practice built on it: making sure a provider and its consumers keep honouring a shared contract on every change, which also includes breaking-change diffs and, in consumer-driven setups, verifying each consumer's own expectations.
Sources and further reading
- OpenAPI Specification: how operations, parameters and response schemas are described.
- JSON Schema specification: the schema language OpenAPI 3.1 uses for bodies.
- Ajv documentation: the JavaScript JSON Schema validator used in the examples.
- Ajv OpenAPI support: how Ajv handles
nullableanddiscriminator. - openapi-core: Python request and response validation against OpenAPI.
- REST Assured usage guide: includes the JSON Schema validation module.
- Schemathesis: property-based testing from OpenAPI.
- Schemathesis GitHub Action: the
schemathesis/action@v3step used in the CI job. - oasdiff-action: breaking-change checks between two OpenAPI files in GitHub Actions.
- Prism: mock server and validating proxy for OpenAPI.
- Amazon API Gateway request validation
- Azure API Management validate-content policy
- Cloudflare API Shield schema validation
- oasdiff: breaking-change detection between two OpenAPI documents.
Want schema-aware tests generated from your own spec, with a breaking-change review every time it changes? Start a free trial and import your OpenAPI document.
Go deeper in the Learning Center
Hands-on lessons with runnable code against our live sandbox.
Schema validation in API testing happens in three places: requests, responses, and the spec itself as it changes. Find real drift between the sandbox store and its spec, then see how Shift-Left API catches both kinds.
Most API bugs live in input validation. Here's how to test it systematically.
Fifteen conventions that make REST APIs a joy to use — and the absence of any one is a smell.
Ready to shift left with your API testing?
Import your OpenAPI spec and get a runnable test suite, in our cloud or on your own infrastructure.