OpenAPI, Contract & Schema Testing

API Schema Validation: What It Is, How to Do It, Tools

Parveen KumariUpdated 20 min read
Quick answer

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

Share:
API schema validation comparing a live API response against the OpenAPI schema in a CI pipeline

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

  1. What is API schema validation?
  2. What schema validation checks
  3. How to do API schema validation in tests
  4. Schema validation in CI and at the API gateway (with a complete GitHub Actions job)
  5. API schema validation tools
  6. Schema drift: when the API and the spec disagree
  7. Best practices and common pitfalls
  8. 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:

CheckRequest sideResponse side
Status coden/aIs it one the operation documents?
Content typeDoes Content-Type match a declared media type?Does the response media type match?
ParametersPath, query, header and cookie parameters: presence, type, format, enumn/a
Body: required fieldsAre required properties present?Are required properties present?
Body: types and formatsstring, integer, boolean, array, object; date-time, uuid, email, uriSame
Body: constraintsminimum/maximum, minLength/maxLength, pattern, enumSame
Nullabilitynullable: true (3.0) or type: [string, "null"] (3.1)Same
Unknown fieldsRejected only where additionalProperties: falseSame
HeadersRequired request headersDocumented 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-validators extension. Failing requests get a 400 without invoking the integration. HTTP APIs do not offer this feature.
  • Azure API Management. The validate-content policy validates the size and content of request or response bodies against the API's schemas (JSON or XML), with companion validate-parameters, validate-headers and validate-status-code policies. Each can be set to prevent (block), detect (log only) or ignore, 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

ToolWhat it validatesWhere it runsNotes
AjvAny JSON value against JSON Schema (draft-07, 2019-09, 2020-12)Node.js tests, browsersFast, compiled validators; add ajv-formats for formats
openapi-coreRequests and responses against OpenAPI 3.0/3.1Python tests and middlewareChecks status codes and media types, not only bodies
REST Assured json-schema-validatorResponse body against a JSON Schema fileJava testsPair with Atlassian swagger-request-validator for full OpenAPI checks
Atlassian swagger-request-validatorRequests and responses against OpenAPIJava (REST Assured, MockMvc, WireMock)Validates against the spec, not a copied schema
Postman jsonSchemaResponse body against JSON SchemaPostman, Newman, Postman CLItv4 is the deprecated predecessor
express-openapi-validatorRequests and optionally responsesNode.js Express middlewareValidation inside the service itself
SchemathesisResponses for generated inputs across the whole specCLI, pytest, CIProperty-based; finds crashes as well as schema violations
PrismRequests and responses passing through a proxyCLI, CIAlso serves mocks from the spec
DreddResponses against spec examplesCLI, CIExample-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 requestsProduction edgeBlocks 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.

Free PDF + code examples

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.

We email you the download link. No spam, unsubscribe any time.

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.

Six types of API schema drift showing type changes, added fields, removed fields, format changes, nullable changes, and nested structure changes

The six common forms:

  1. Type changes. An integer becomes a string, or an array becomes a single object. Typed clients fail to deserialize.
  2. Required-field changes. A required field disappears, or a field the spec calls optional becomes one the client depends on.
  3. Removed or renamed fields. The most immediately destructive: the client reads undefined.
  4. Format changes. Same type, different shape: ISO 8601 dates become Unix timestamps, integer IDs become UUID strings. Type checks pass; format checks catch it.
  5. Nullable transitions. A field that was never null starts returning null for some data states. It appears intermittently, so it is hard to reproduce.
  6. Nested restructuring. data.user.name becomes user_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.

Schema validation in CI/CD pipeline showing developer commit through validation checks with pass/fail branching

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. Document 400, 401, 403, 404, 409, 422 and 500 bodies (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 uses type: [string, "null"]. A 3.1 validator ignores nullable, which produces false failures or, worse, false passes. See OpenAPI 3.1 vs 3.0 for testing.
  • Decide deliberately on additionalProperties. false on 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 format unless you add ajv-formats; other validators differ too. Check that email, uuid and date-time are 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 $ref did not resolve.
  • Model optional fields correctly. If a field is sometimes absent, leave it out of required; if it is sometimes null, 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 required arrays 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

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.

Continue learning

Go deeper in the Learning Center

Hands-on lessons with runnable code against our live sandbox.

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.