JSON syntax tells you whether a document is well formed, but it says nothing about whether the data is right. Is age a number? Is email present? Is status one of the three allowed values? JSON Schema answers those questions. It is a vocabulary, itself written in JSON, for describing and validating the shape of JSON documents. In this lesson of our JSON tutorial series, we write real schemas and validate data against them.
APIs receive input from clients you do not control. Without validation, a missing field surfaces as a confusing undefined error deep in your business logic, or worse, bad data lands in your database. Validating at the boundary turns those failures into immediate, precise 400 responses.
Here is a schema describing a user object:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 13 },
"role": { "type": "string", "enum": ["admin", "editor", "viewer"] }
},
"required": ["name", "email"],
"additionalProperties": false
}Reading it top to bottom: the document must be an object; four properties are described with their types and constraints; name and email are mandatory; and no unknown keys are allowed.
object, array, string, number, integer, boolean, null.minLength / maxLength for strings.false to reject unexpected keys.Schemas compose the same way JSON does. An orders array is described with items:
{
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"sku": { "type": "string" },
"qty": { "type": "integer", "minimum": 1 }
},
"required": ["sku", "qty"]
}
}JavaScript projects typically use the Ajv library, and Python projects use the jsonschema package:
import Ajv from "ajv";
const ajv = new Ajv();
const validate = ajv.compile(userSchema);
if (!validate(input)) console.log(validate.errors);Validation errors report the failing path and rule, for example /age must be >= 13, which you can return directly in an API error envelope.
JSON Schema also powers editor autocompletion for configuration files (VS Code uses schemas from schemastore.org), contract documentation in OpenAPI specifications, and code generation for typed clients. Writing the schema first, a design-first workflow, keeps server, clients, and documentation in agreement.
type, required, enum, bounds, and items cover the vast majority of real schemas.Next up: Common JSON Errors and How to Fix Them, a field guide to the mistakes every developer eventually makes.