Learn how to define, validate, and document your JSON data structures using JSON Schema — the standard for API contracts.
JSON Schema is a vocabulary that allows you to annotate and validate JSON documents. It acts as a contract between your API and its consumers, ensuring data always matches the expected shape.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["name", "email"],
"properties": {
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0 }
}
}
| Type | Example |
|---|---|
string | "hello" |
number | 3.14 |
integer | 42 |
boolean | true |
array | [1, 2, 3] |
object | {"a": 1} |
null | null |
minLength / maxLength — string length constraintsminimum / maximum — number rangepattern — regex for stringsenum — allowed valuesrequired — mandatory keys{
"type": "object",
"properties": {
"tags": { "type": "array", "items": { "type": "string" } },
"address": { "type": "object", "properties": { "city": { "type": "string" } } }
}
}
import Ajv from "ajv";
import addFormats from "ajv-formats";
const ajv = new Ajv();
addFormats(ajv);
const schema = {
type: "object",
required: ["email"],
properties: { email: { type: "string", format: "email" } }
};
const validate = ajv.compile(schema);
const valid = validate({ email: "test@example.com" });
if (!valid) console.log(validate.errors);