Development2024-05-26

JSON Schema Validation: The Complete Guide to Bulletproof APIs

If your API accepts JSON without validation, you're inviting chaos. JSON Schema is the industry standard for validation — here's how to use it properly.

#json-schema#validation#api#backend#best-practices

Hi back-end boys and girls 👋

Today's topic: JSON Schema. If you're not validating your API inputs with schemas, you're not doing backend — you're playing Russian roulette with data.

Let me fix that.

What Is JSON Schema?

JSON Schema is a vocabulary for describing JSON structure. It defines:

  • Required fields
  • Data types (string, number, boolean, object, array)
  • Value constraints (min, max, pattern, enum)
  • Nested object structures

A Real Example

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["name", "email", "age"],
  "properties": {
    "name": { "type": "string", "minLength": 2, "maxLength": 100 },
    "email": { "type": "string", "format": "email" },
    "age": { "type": "integer", "minimum": 0, "maximum": 150 },
    "role": { "type": "string", "enum": ["admin", "user", "viewer"] }
  },
  "additionalProperties": false
}

This schema enforces:

  • name is required, 2-100 characters
  • email is required, must be valid email format
  • age is required, integer between 0-150
  • role is optional, must be one of three values
  • No extra fields allowed

How to Generate Schemas

Option 1: Write manually (tedious for large APIs) Option 2: Use a JSON Schema Generator — paste a sample JSON, get the schema automatically

Validation in Code

JavaScript (with ajv)

import Ajv from "ajv";
const ajv = new Ajv();

const validate = ajv.compile(schema);
const valid = validate(data);

if (!valid) {
  console.log(validate.errors);
  // [{ "message": "must have required property 'email'" }]
}

Python (with jsonschema)

import jsonschema

try:
    jsonschema.validate(instance=data, schema=schema)
except jsonschema.ValidationError as e:
    print(f"Validation error: {e.message}")

Common Schema Patterns

Nullable Fields

{ "type": ["string", "null"] }

Conditional Validation

{
  "if": { "properties": { "type": { "const": "business" } } },
  "then": { "required": ["companyName", "taxId"] }
}

Array Validation

{
  "type": "array",
  "items": { "type": "string", "format": "email" },
  "minItems": 1,
  "maxItems": 100,
  "uniqueItems": true
}

Schema Best Practices

  1. Always set additionalProperties: false — Reject unexpected fields
  2. Use format for validation — email, uri, date, uuid
  3. Version your schemas/v1/user-schema.json
  4. Generate documentation from schemas — Tools like json-schema-for-humans
  5. Test your schemas — Use positive and negative test cases

The Ecosystem

Tool Purpose
ajv (JS) Fast validation
jsonschema (Python) Standard validation
JSON Schema Generator Auto-generate from samples
JSON Formatter Validate JSON syntax
JSON Compare Diff schema versions

Generate JSON Schema from sample data with our free JSON Schema Generator — instant validation schemas, supports all JSON Schema draft versions.

🛠

Try It Yourself

Put what you've learned into practice with our free online tools.

Explore More Developer Tools

Discover more tools and tutorials in this category

Browse Category →