JSON Schema: Validating JSON With a Schema
A JSON Schema describes the shape of a JSON document. Learn the types, the constraints, the composition, and the validation.
By Velloreth
The idea
A JSON Schema describes the shape of a JSON document.
A validator checks a document against it.
It is written in JSON, which makes it portable.
The basic schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 0 },
"email": { "type": "string", "format": "email" }
},
"required": ["name", "email"],
"additionalProperties": false
}
type is the JSON type.
properties lists the allowed keys.
required lists the keys that must be present.
additionalProperties: false rejects an unknown key.
The types
| Type | Notes |
|---|---|
string | with minLength, maxLength, pattern, format |
number | with minimum, maximum, multipleOf |
integer | a number with no fraction |
boolean | true or false |
object | with properties, required |
array | with items, minItems, uniqueItems |
null | the null value |
A type can be a list.
{ "type": ["string", "null"] }
The constraints
{
"type": "string",
"minLength": 3,
"maxLength": 100,
"pattern": "^[a-z0-9-]+$"
}
{
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"uniqueItems": true
}
format is an annotation, and a validator may or may not enforce it.
| Format | Meaning |
|---|---|
email | an email address |
uri | a URI |
date-time | an ISO 8601 timestamp |
uuid | a UUID |
ipv4 | an IPv4 address |
The composition
| Keyword | Meaning |
|---|---|
allOf | every subschema must match |
anyOf | at least one must match |
oneOf | exactly one must match |
not | must not match |
{
"oneOf": [
{ "type": "object", "required": ["cardNumber"] },
{ "type": "object", "required": ["iban"] }
]
}
oneOf is the strictest, because a document that matches two subschemas fails.
The reference
{
"properties": {
"author": { "$ref": "#/$defs/User" }
},
"$defs": {
"User": {
"type": "object",
"properties": { "id": { "type": "string" } },
"required": ["id"]
}
}
}
$ref avoids a duplication.
A local reference uses a JSON Pointer.
A remote reference uses a URL, which requires a fetch.
The validation
import Ajv from 'ajv';
const ajv = new Ajv();
const validate = ajv.compile(schema);
if (!validate(data)) {
console.error(validate.errors);
}
Ajv is the common JavaScript validator.
A validator reports the errors with a path and a message.
A strict mode rejects an unknown keyword, which catches a typo.
The code generation
A tool generates a type from the schema.
// generated from the schema
interface User {
id: string;
name: string;
email?: string;
}
The schema is the source of truth, and the type is derived.
That keeps the validation and the type in sync, which is the main benefit.
The use cases
| Use | Benefit |
|---|---|
| An API payload | a contract |
| A config file | a caught typo |
| A form | a generated UI |
| A message | a validated event |
| A test fixture | a known shape |
An OpenAPI document uses a JSON Schema for the request and the response.
The schema in an API
A schema is most valuable at the boundary of a service, because that is where a misunderstanding becomes a bug. The request body is validated against a schema before the handler runs, so the handler can assume the shape and the types, and an invalid request is rejected with a clear error rather than failing deep in the code. The response is validated in a test, so a change to the handler that breaks the contract is caught before it ships. The schema is also the source of the documentation, because a tool generates the API reference from it, and the source of the client, because a tool generates a typed client. The discipline that makes it work is that the schema is the source of truth and the code is derived from it, because a schema that is written after the code drifts from it within a release or two.
The versioning
A schema is a contract, and a contract that changes without a version breaks a consumer. The safe changes are to add an optional property, to widen a constraint, and to add a new value to an enum that the consumer treats as unknown. The breaking changes are to add a required property, to remove a property, to narrow a constraint, and to change a type. A version in the URL or in a header is the common way to signal a break, and a deprecation period gives the consumer time to migrate. A schema that is validated in the pipeline catches the accidental break, because a change that removes a required property fails the test that validates the old fixture.
Common mistakes
No additionalProperties: false. A typo is accepted.
A format assumed to be enforced. It may be an annotation.
A oneOf that matches two. A surprising failure.
No $schema. The draft is ambiguous.
A $ref to a remote URL. A fetch at validation time.
A schema that is not versioned. A breaking change.
A validation on the client only. A security hole.
A large schema in one file. Hard to maintain.
No error message. The user does not know what is wrong.
A schema that is out of sync with the code. A false confidence.
A quotable summary
A JSON Schema describes the shape of a JSON document, and a validator checks a document against it and reports the errors. The core keywords are type, properties, required and items, composition uses allOf, anyOf, oneOf and not, and additionalProperties: false rejects an unknown key. A schema is a contract, so it should be versioned, and a tool can generate a type or a form from it.
Related reading
For the related topics, see form-validation-patterns and rest-api-design-principles. For the broader context, api-error-responses-guide and json-vs-yaml-vs-toml.