JSON Schema: Validating API Data Like a Pro
TL;DR
Learn how to define structural types, required properties, and string constraints using JSON Schema (draft-07 / draft-2020-12). Enforce strict API contracts across microservices.
Try the Interactive Tool
Paste a schema with a required field and a payload missing that field into JSON Schema Validator to inspect the error path.
As microservice architectures scale, enforcing data contracts between independent service boundaries becomes paramount. Without strict validation gates, corrupted payloads or missing fields can propagate deep into downstream database operations, triggering unhandled runtime exceptions.
JSON Schema is a declarative vocabulary for annotating and validating JSON documents.
1. Anatomy of a JSON Schema
A JSON Schema document specifies expected types, property requirements, and value constraints:
Worked example
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "UserRegistrationPayload",
"type": "object",
"properties": {
"userId": {
"type": "string"
},
"username": {
"type": "string",
"minLength": 3,
"maxLength": 30
},
"age": {
"type": "integer",
"minimum": 18
},
"roles": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1
}
},
"required": ["userId", "username", "age"]
}
2. Essential Validation Keywords
Numeric Constraints
- minimum / maximum: Inclusive bounds.
- exclusiveMinimum / exclusiveMaximum: Strict inequality bounds.
- multipleOf: Asserts that a number is a multiple of a given base value (e.g., "multipleOf": 0.01 for currency formats).
String Constraints
- minLength / maxLength: String length validation.
- pattern: Regex matching (e.g., "pattern": "^[A-Z]{3}-\d{4}$").
- format: Labels values such as email, URI, and dates. Enforcement depends on the validator and configuration. The site does not register the Ajv formats plugin, so a schema with an unknown format can fail to compile. Use a constraint the validator recognizes or register the format in your service.
3. Combining Schemas with oneOf, anyOf, and allOf
JSON Schema supports complex composition operators:
- allOf: Payload must satisfy all nested sub-schemas (useful for combining base traits with specific extensions).
- oneOf: Payload must satisfy exactly one sub-schema (ideal for polymorphic API responses).
- anyOf: Payload must satisfy one or more sub-schemas.
Auto-Generate Schemas from Example JSON
Don't waste time hand-writing boilerplate schema definitions. Infer a starter JSON Schema from an example document using our client-side JSON Schema Generator or test payloads with our JSON Schema Validator.
Walk a failing order through the validator
An order producer is starting to send a trace field and has accidentally omitted orderId. A line item has quantity zero. All three issues can occur in a JSON document that is syntactically valid. Paste this contract into the Schema editor of JSON Schema Validator, then paste the payload into its Data editor.
{
"type": "object",
"required": ["orderId", "items"],
"additionalProperties": false,
"properties": {
"orderId": { "type": "string" },
"items": { "type": "array", "items": { "$ref": "#/definitions/item" } }
},
"definitions": {
"item": {
"type": "object",
"required": ["sku", "quantity"],
"properties": {
"sku": { "type": "string" },
"quantity": { "type": "integer", "minimum": 1 }
}
}
}
}
{"items":[{"sku":"A","quantity":0}],"trace":true}
The validator reports these paths and messages for that input. The UI renders an empty instance path as root.
root must have required property 'orderId'
root must NOT have additional properties
/items/0/quantity must be >= 1
The last line points at the quantity on the first item. The required error points at the containing object because the absent member has no location in the payload. Likewise, the extra-field error belongs to the object whose field set failed validation. When logging errors in a service, preserve the validator's additional property or missing property parameter if it is available. That makes the message actionable when there are several unknown or absent fields at the same level.
Fix the producer by adding its real identifier, removing the uncontracted field, and sending a positive quantity. This corrected fixture validates with an empty errors array.
{"orderId":"o-42","items":[{"sku":"A","quantity":1}]}
If the trace field is intentional, agree on it in the contract before silently stripping it. A debug field that starts out optional can become relied on by a downstream consumer. Removing it as a side effect of validation hides that relationship. Decide whether it belongs in the payload, a transport header, or a separate telemetry stream.
Three schema choices that change the result
Properties do not imply required
Listing a property constrains its value when present. It does not require the property to appear. Add a required array to the object schema that owns the field. In the order example, the root requires orderId and items. The definition under items separately requires sku and quantity. Moving every requirement to the root would check for those item fields at the wrong location.
Presence and value are separate checks. An empty string satisfies the type string and the requirement to be present. If orderId must have at least one character, add minLength. If whitespace-only values must also be rejected, decide how the application trims and validates them. Similarly, a field present with null fails a string-only schema even though it satisfies required. Add null to the allowed type only when the receiving service has a meaning for it.
Close each object deliberately
Additional properties are allowed unless restricted. The example closes the outer object but leaves the line item open. Adding additionalProperties: false to the root will not reject an unrecognized key inside items. Put the restriction on the item definition if strict line items are part of the contract. For external clients, think about whether strict consumers will break when a producer adds optional information. Strict validation can be valuable for a request command where unexpected fields suggest a misspelling. It can be inconvenient for a response consumer that only needs a subset and should tolerate compatible additions.
Resolve references with the right base URI
The reference #/definitions/item points inside the submitted schema. Replacing it with a URL assumes the validator has the referenced schema registered or can resolve it. The browser tool compiles the pasted schema locally and does not fetch external references. For an isolated reproduction, move the referenced definition into the document and update the reference to its local fragment. In a service, register the dependency with the validator before compiling and keep its version explicit. If a schema sets an identifier, check the base URI used to resolve relative paths, especially after moving definitions between files.
Version a contract across service boundaries
Keep a passing fixture and a deliberate failure for every contract change. A producer can test the next payload against the old schema before it rolls out. A consumer can check that its next schema still accepts examples from the deployed producer. During a staged rollout, both versions may run at the same time, so test both directions. A seemingly safe addition can fail when the older consumer closes its object, and a newly required field can fail if the older producer has not started sending it.
For a breaking revision, route by an explicit version, versioned media type, or other agreed boundary. Keep the old contract while older producers or consumers are still active. Count rejection reasons by contract version and error path rather than logging entire customer payloads. Once both sides agree on the new fixtures, remove compatibility handling intentionally rather than leaving a permissive schema that accepts ambiguous input indefinitely.