JSON Schema Validation Guide โ Validate API Payloads With Structure Rules
JSON Schema lets you define the expected shape of a JSON object and validate inputs against it. Here is a practical guide to writing schemas.
JSON Schema is a vocabulary for describing the structure of JSON data. It lets you define what valid data looks like, validate incoming data against that definition, and generate documentation automatically. It's more powerful than syntax checking and more flexible than static typing.
Basic JSON Schema structure
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 1
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"role": {
"type": "string",
"enum": ["admin", "user", "moderator"]
}
},
"required": ["id", "name", "email"]
}Validating with ajv in Node.js
import Ajv from "ajv";
import addFormats from "ajv-formats";
const ajv = new Ajv();
addFormats(ajv); // adds "email", "date-time", etc.
const validate = ajv.compile(schema);
const data = { id: 1, name: "Alice", email: "alice@example.com" };
if (validate(data)) {
console.log("Valid!");
} else {
console.error("Validation errors:", validate.errors);
// [{ instancePath: "/email", message: "must match format "email"" }]
}Nested objects and arrays
{
"type": "object",
"properties": {
"orders": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "string" },
"total": { "type": "number", "minimum": 0 },
"status": {
"type": "string",
"enum": ["pending", "shipped", "delivered", "cancelled"]
}
},
"required": ["id", "total", "status"]
},
"minItems": 1
}
}
}Using schemas in APIs
Validate incoming request bodies at the API gateway or middleware level. This means your business logic only ever sees valid data:
// Express middleware
app.post("/users", validateBody(userSchema), async (req, res) => {
// req.body is guaranteed valid here
const user = await createUser(req.body);
res.status(201).json(user);
});Test JSON responses with our JSON Formatter before building schemas around them.