JSON Schema Primer: Validate API Payloads Before They Break Your App

●2 ●92 ●140
calendar_today • schedule3 min read

The Problem JSON Schema Solves

APIs receive bad data. A field expected to be an integer arrives as a string. A required field is missing. An email field contains "not-an-email". Without validation, these problems surface deep inside your application logic — often as cryptic runtime errors, not clear validation messages.

JSON Schema is the industry-standard solution: a declarative language for describing exactly what valid JSON should look like. Write the schema once, validate anywhere.

What Is a JSON Schema?

A JSON Schema is a JSON document that describes the structure and constraints of another JSON document.

{
  "type": "object",
  "required": ["id", "email"],
  "properties": {
    "id":    { "type": "integer", "minimum": 1 },
    "email": { "type": "string", "format": "email" }
  },
  "additionalProperties": false
}

This schema accepts objects with an integer id (at least 1) and a valid email string. Any extra fields are rejected.

The Draft Versions

JSON Schema has several published drafts. Draft-07 is the most important to know:

  • Used by OpenAPI 3.0 (the Swagger standard for REST APIs)
  • Supported by Ajv (JavaScript), jsonschema (Python), and most tooling
  • Added if/then/else conditional validation
  • Still the most widely deployed version in production

Draft 2020-12 is newer but draft-07 is what you'll encounter in existing codebases and tooling.

Core Keywords

Types

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

Types: string, number, integer, boolean, null, array, object. An array of types means "any of these".

String Validation

{
  "type": "string",
  "minLength": 3,
  "maxLength": 50,
  "pattern": "^[a-z0-9_]+$",
  "format": "email"
}

format options: email, uri, date (YYYY-MM-DD), date-time, ipv4, hostname.

Number Validation

{
  "type": "number",
  "minimum": 0,
  "maximum": 100,
  "multipleOf": 0.01
}

Use exclusiveMinimum/exclusiveMaximum for strict bounds (in draft-07, these take numeric values).

Array Validation

{
  "type": "array",
  "items": { "type": "string" },
  "minItems": 1,
  "maxItems": 20,
  "uniqueItems": true
}

When items is a schema, every element must match it. For tuple validation (different schema per position), set items to an array of schemas.

Object Composition

{
  "type": "object",
  "required": ["name"],
  "properties": {
    "name": { "type": "string" },
    "role": { "type": "string", "enum": ["admin", "user"] }
  },
  "additionalProperties": false
}

required lists mandatory keys. additionalProperties: false rejects undeclared keys.

Schema Composition

allOf, anyOf, oneOf

  • allOf — must be valid against every schema (AND)
  • anyOf — must be valid against at least one schema (OR)
  • oneOf — must be valid against exactly one schema
{
  "oneOf": [
    { "properties": { "type": { "const": "circle" } }, "required": ["radius"] },
    { "properties": { "type": { "const": "rect" } }, "required": ["width", "height"] }
  ]
}

This is a discriminated union: exactly one branch matches based on the type field.

Reusable Definitions with $ref

{
  "$defs": {
    "Address": {
      "type": "object",
      "required": ["street", "city"],
      "properties": {
        "street": { "type": "string" },
        "city":   { "type": "string" },
        "zip":    { "type": "string", "pattern": "^\\d{5}$" }
      }
    }
  },
  "type": "object",
  "properties": {
    "billing":  { "$ref": "#/$defs/Address" },
    "shipping": { "$ref": "#/$defs/Address" }
  }
}

Define a schema once in $defs, reference it anywhere with $ref. Eliminates duplication.

Conditional Validation with if/then/else

{
  "if":   { "properties": { "plan": { "const": "paid" } }, "required": ["plan"] },
  "then": { "required": ["paymentMethod"] },
  "else": {}
}

If plan equals "paid", then paymentMethod is required. If plan is anything else, no additional constraint applies.

Validate in Your Browser

You can test JSON Schema immediately — no installation needed. Paste your schema on the left, paste your JSON on the right, and see clear path-based error messages (e.g. $.user.address.zip) in real time:

JSON Schema Validator — SnappyTools

Entirely client-side — your data never leaves the browser. Safe for API payloads with credentials or private configuration.

Validate in Code

JavaScript (Node.js):

npm install ajv ajv-formats
import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv();
addFormats(ajv);

const validate = ajv.compile(schema);
if (!validate(data)) {
  console.error(validate.errors);
}

Python:

pip install jsonschema
from jsonschema import validate, ValidationError

try:
    validate(instance=data, schema=schema)
except ValidationError as e:
    print(e.message, list(e.absolute_path))

Schemas written for the browser tool work identically in both libraries — same standard, no rewriting.

Common Errors Explained

"Additional property not allowed" — your JSON has a field not listed in properties, and the schema has additionalProperties: false. Add the field to the schema or remove it from the JSON.

"Missing required property" — a field listed in required is absent from the JSON. Either add it or remove it from required.

"Expected type integer, got string" — the JSON field is a quoted string ("42") where the schema expects a number (42). Remove the quotes.

"Value must match exactly one schema in oneOf (matched 0)" — the data doesn't match any branch. Check the discriminator field and the branch conditions.

Summary

KeywordPurpose
typeRestrict to a JSON type
properties + requiredDefine expected object fields
additionalPropertiesControl unknown fields
enum / constRestrict to fixed values
minLength / maxLengthString length bounds
minimum / maximumNumeric bounds
itemsArray element schema
allOf / anyOf / oneOfSchema composition
$ref + $defsReusable definitions
if / then / elseConditional validation

JSON Schema is the cheapest way to catch data problems before they reach your application logic. Write it once, validate everywhere.

Originally published at https://snappytools.app/json-schema-validator/

Want more #webdev & #javascript deep dives?

Join 6,139+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

Free SEO Tools Every Small Business Should Use (2026) | FloxoLab

floxolab - Oct 20

The Zero-Net-Loss Fleet & The Mercenary Squad: A Live AI Economy

DEVPlank - Aug 4

What Security Teams Want From AI Agents Before They Let Them Act Alone

Tom Smithverified - Nov 18

Merancang Backend Bisnis ISP: API Pelanggan, Paket Internet, Invoice, dan Tiket Support

Masbadar - Mar 13

Stop Turning Every REST Endpoint into an MCP Tool: A Better Approach to AI Tool Design

zeekwrites - Nov 30
chevron_left
2.5k Points • 234 Badges
102Posts
0Comments
SnappyTools builds free, fast, browser-based tools for developers, writers, and designers. No signup... Show more

Related Jobs

View all jobs →

Commenters (This Week)

3 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!