📐

JSON Schema

JSON Schema is a formal specification that describes the expected structure of a JSON object: which properties exist, what data types they contain, which are required, and what constraints they must meet. It's widely used to validate requests and responses in REST APIs, generate automatic documentation, and ensure contracts between frontend and backend.

Examples

  • { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": ["email"], "properties": { "email": { "type": "string", "format": "email" } } }
  • { "type": "array", "items": { "type": "number" }, "minItems": 1, "uniqueItems": true }
  • { "type": "string", "pattern": "^[A-Z]{3}-\\d{4}$", "description": "Product code" }
  • { "oneOf": [{ "type": "string" }, { "type": "number" }] }
  • { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string", "minLength": 1 } } }

FAQ

What's the difference between draft-07 and draft 2020-12?

Draft 2020-12 replaces 'definitions' with '$defs', introduces '$dynamicRef' for dynamic recursion, and improves annotation vocabulary ('deprecated', 'readOnly'). Most libraries still use draft-07; only migrate if you need new features and your validator supports it.

Does JSON Schema validate data or just structure?

It validates both: structure (types, required properties) and data (ranges, patterns, enums). But not complex business logic (e.g., 'this email must exist in the DB'). For that, use custom validators after passing the schema.

How do I handle large schemas without duplication?

Use '$ref' to reference common definitions within the same schema ('$defs') or in external files. Tools like '$RefParser' resolve references and produce a complete schema. You can also use 'allOf' to compose small schemas into a large one.