Validate JSON data with schemas, types, required fields, formats, composition, and API contracts.
Lessons
Verify responses match the documented contract.
Validating API Responses is easiest to learn by reading the example, changing it, and observing the result.
import Ajv from 'ajv';
const ajv = new Ajv({ allErrors: true });
const schema = {
type: 'object',
required: ['slug', 'title'],
properties: {
slug: { type: 'string', pattern: '^[a-z0-9-]+$' },
title: { type: 'string', minLength: 3 }
}
};
const validate = ajv.compile(schema);
const data = { slug: 'json-schema', title: 'JS' };
if (!validate(data)) {
console.log(validate.errors);
}Practice the Validating API Responses example in a small scratch file, then explain what changed and why.