JSON Schema validation gives API teams a repeatable way to check whether request and response payloads have the expected shape before malformed data reaches application logic, databases, or downstream services. This guide explains how to design a reusable schema, validate it with Ajv and Python, produce actionable errors, organize fixtures, and run contract checks in CI.
Overview
A JSON Schema describes the structure and constraints of JSON data. It can define required properties, permitted types, string formats, numeric limits, arrays, nested objects, and whether unexpected properties are accepted. A validator then compares a JSON document with that schema and reports whether the document conforms.
Schema validation is useful at several boundaries:
- Incoming API requests: reject incomplete or incorrectly typed input before business logic runs.
- Outgoing responses: detect accidental contract changes before clients receive them.
- Webhook payloads: verify that an event has the fields your consumer needs.
- Fixtures and test data: catch invalid examples before they make tests misleading.
- CI workflows: make payload checks part of the normal change-review process.
Validation is not a replacement for authentication, authorization, business rules, or database constraints. A schema can establish that quantity is an integer greater than zero, for example, but application code still needs to decide whether the requested quantity is available to the current user.
When a schema is connected to an OpenAPI contract, it can also help keep implementation behavior and generated documentation aligned. For a broader contract workflow, see the OpenAPI validation and testing workflow and the OpenAPI schema validation guide.
Template structure
A practical JSON Schema starts with a clear contract rather than every possible rule. The following example describes a user creation request and is suitable as a starting fixture:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.test/schemas/create-user.json",
"title": "Create user request",
"type": "object",
"additionalProperties": false,
"required": ["email", "displayName"],
"properties": {
"email": {
"type": "string",
"format": "email"
},
"displayName": {
"type": "string",
"minLength": 1,
"maxLength": 80
},
"roles": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true
},
"marketingOptIn": {
"type": "boolean",
"default": false
}
}
}The main building blocks are:
| Keyword | Purpose | Example use |
|---|---|---|
type | Sets the JSON data type. | string, object, array, or integer |
properties | Describes fields in an object. | Define email and displayName. |
required | Lists fields that must be present. | Require identifiers or routing values. |
additionalProperties | Controls undeclared object fields. | Set to false when a strict contract is appropriate. |
items | Describes array elements. | Require every role to be a string. |
enum | Limits a value to known options. | Allow only pending, paid, or cancelled. |
oneOf, anyOf, and allOf | Combines alternative or shared schemas. | Model several event variants. |
Use a draft version deliberately and configure the validator to support the same draft. A schema that declares one draft while the library is configured for another can produce confusing failures, especially around newer keywords and format behavior. Keep the draft choice visible in the schema and in the validator setup.
How to customize
Start by identifying the boundary being protected and the payloads that actually cross it. Then make these decisions:
- Separate request and response schemas. A response may include server-generated identifiers, timestamps, or links that should not be accepted in a create request.
- Decide how strict unknown fields should be. Rejecting additional properties can reveal client mistakes quickly. Allowing them can make independently deployed clients easier to evolve. Choose per endpoint rather than applying one rule everywhere.
- Keep format checks explicit. A format such as
emailmay be useful, but validators can differ in which formats they enable or enforce. Treat format support as part of your test configuration. - Put business rules in the right layer. Use the schema for shape and basic constraints; use application logic for permissions, uniqueness checks, inventory, and state transitions.
- Write stable error handling. Log the keyword, instance path, schema path, and a safe summary. Do not expose internal schema details or sensitive payload values to untrusted callers.
For API debugging, compare the actual request and response with the validated fixture rather than relying only on an error message. The Chrome DevTools Network Panel guide can help trace headers, payloads, and response timing when a browser client behaves differently from a test.
Ajv JSON validation in Node.js
Ajv is commonly used in JavaScript and TypeScript services. The exact package configuration should match the draft used by your schemas. This example shows the basic flow:
import Ajv from "ajv";
import addFormats from "ajv-formats";
import schema from "./create-user.schema.json" with { type: "json" };
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile(schema);
const payload = {
email: "[email protected]",
displayName: "Dev User",
roles: ["reader"]
};
if (!validate(payload)) {
console.error(validate.errors);
throw new Error("Payload failed JSON Schema validation");
}
console.log("Payload is valid");allErrors: true can be useful in tests because it reports more than the first failure. In a high-volume request path, teams may choose a different setting and return a concise client-facing error while retaining structured diagnostic details in controlled logs.
Python validation
In Python, the jsonschema package provides a straightforward validation interface. Select the validator class that corresponds to the schema draft your project uses:
import json
from jsonschema import Draft202012Validator
with open("create-user.schema.json", encoding="utf-8") as file:
schema = json.load(file)
payload = {
"email": "[email protected]",
"displayName": "Dev User",
"roles": ["reader"]
}
validator = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(payload), key=lambda error: list(error.path))
if errors:
for error in errors:
path = ".".join(str(part) for part in error.path) or "$"
print(f"{path}: {error.message}")
raise SystemExit(1)
print("Payload is valid")Sorting errors by their instance path makes command-line output more consistent and easier to compare in CI logs.
Examples
Useful error messages
Suppose a payload omits displayName, uses a number for email, and includes an undeclared field. A validator may return low-level errors such as a required-property failure, a type failure, and an additional-property failure. Convert these into a consistent application format:
[
{
"path": "$/displayName",
"code": "required",
"message": "displayName is required"
},
{
"path": "$/email",
"code": "type",
"message": "email must be a string"
},
{
"path": "$/debugToken",
"code": "additionalProperties",
"message": "debugToken is not allowed"
}
]Keep the original validator error available for developers, but give API consumers a stable code and path. Avoid echoing secrets, authorization tokens, or complete request bodies in error responses.
Fixture layout
A small, predictable fixture structure makes contract checks easier to maintain:
schemas/
create-user.schema.json
fixtures/
create-user.valid.json
create-user.missing-display-name.json
create-user.unknown-property.json
tests/
payload-schema.test.jsInclude at least one valid fixture and focused invalid fixtures for each important rule. Keep invalid examples narrow: a fixture intended to test a missing field should not also contain an invalid email and an unexpected property. This makes failures easier to diagnose.
CI check
Run schema tests whenever a schema, fixture, endpoint handler, or generated API contract changes. A generic workflow is:
- Install dependencies from the lockfile.
- Load schemas and compile them with the configured draft.
- Validate every fixture.
- Assert that valid fixtures pass and intentionally invalid fixtures fail.
- Fail the job when a fixture produces an unexpected result.
Dependency update tools can help keep the validator library and related format packages current, but upgrades should still be reviewed against your schemas and test fixtures. See the Renovate versus Dependabot workflow guide for a broader maintenance pattern.
For webhook contracts, combine fixture validation with captured or replayed requests. The webhook testing and replay guide provides a useful companion workflow.
When to update
Revisit this guide, your schemas, and your validation tests whenever the underlying contract changes. The most important triggers are:
- A request or response field is added, removed, renamed, or changes type.
- An endpoint introduces a new event variant or nested object.
- A validator, format package, runtime, or schema draft configuration changes.
- A CI failure reveals that fixtures and implementation behavior have drifted.
- A client reports an unclear validation error or receives data it cannot safely parse.
- A webhook provider or internal producer changes its payload shape.
Before merging a schema change, document whether it is backward compatible for existing clients. Add or revise fixtures that represent both the intended new behavior and the important old behavior. If a field becomes required, consider whether older clients can still send valid requests; if a response property is removed, check consumers before deploying the change.
A practical maintenance routine is to review validator configuration and examples at least twice a year, and sooner after a major library or specification update. Keep the schema draft, package configuration, fixture expectations, and error-handling code in the same review path. Finally, run one complete contract check locally before opening a pull request, then let CI repeat it on every change. That combination turns JSON Schema from a reference document into a working guardrail for API payloads.