What a Contract Solves
JSON Schema answers what syntax validation cannot: whether a field exists, whether its type is right, whether a value is in range. Without it, price arriving as "128.5" or a missing userId surfaces only at runtime as a 500—and neither human review nor intuition-driven testing catches that class of bug.
A Minimal Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "total"],
"properties": {
"id": { "type": "string", "minLength": 1 },
"total": { "type": "number", "minimum": 0 },
"items": { "type": "array", "minItems": 1,
"items": { "type": "object",
"properties": {
"sku": { "type": "string" },
"price": { "type": "number", "minimum": 0 }
}, "required": ["sku", "price"] } },
"status": { "enum": ["paid", "pending", "cancelled"] }
}
}
It fixes four hard rules: id/total required, total ≥ 0, items a non-empty array whose elements carry sku+price, and status limited to three values.
Keyword Cheat Sheet
| Keyword | Purpose |
|---|---|
type |
object/array/string/number/integer/boolean/null |
required |
required field list |
properties |
per-field sub-schemas of an object |
items / prefixItems |
array element schema |
enum |
allowed value set |
const |
fixed value (discriminator) |
allOf/anyOf/oneOf |
combine multiple sub-schemas |
$ref |
reference an already-defined schema (reuse) |
format / pattern |
format and regex constraints |
Tightening a Generated Schema
Auto-generation yields loose inference: nullable fields, nullable arrays, and any extra property allowed. Turning it into a contract that rejects bad data takes three moves: put mandatory fields into required; add domain limits (enum/format/minimum/minItems); extract reusable objects into $defs and $ref them.
required Only Guarantees "Key Present"
required says nothing about the value, which is the most misread part:
{"id": null}satisfiesrequired: ["id"], but{"id": {"type": "string"}}reports a type error; allowing null means declaring["string", "null"].{"id": ""}also satisfies required; onlyminLength: 1stops it—mandatory is not the same as non-empty.- A nested
requiredis checked only when the outer property exists:{"user": {}}reports missing fields inside user, while{}(user absent entirely) does not, unless the outer object also listsuseras required.
oneOf: Two Forms That Always Fail
Discriminated unions are written as oneOf with a const discriminator in each branch. Two traps are guaranteed:
The discriminator is not in required. properties constrains keys that appear, not keys that must appear. Given {"to":"a@b.c"} with no type, the email branch still passes (it only requires to), and the sms branch may pass too—both hit, oneOf demands exactly one, and the document fails.
The branches are not mutually exclusive. If the email branch constrains only to and the sms branch only phone, data carrying both satisfies both and fails again. Exclusivity must come from the const discriminator, never from which field is present.
Generating Types From a Schema
Once the schema is the single source of truth, types are just its translation: JSON sample → schema → TypeScript/Go definitions, the first hop through a generator and the second through converters such as schema-to-typescript and schema-to-go.
Inferring types from JSON is fast but reflects one sample, losing absent fields and constraints; deriving from the schema preserves enum/required/nullable, and the generated DTOs share a source with runtime validation—so "the type says required while the validator lets it through" cannot happen.
Landing Checklist
- One versioned schema per endpoint, reviewed with the code;
- Start with a generator (JSON → JSON Schema), then add required and domain limits by hand;
- Runtime validation and type generation share the same schema; discriminated unions always use
oneOf + const.
Reproducible Results
JSON Schema is "data describing data"; twenty lines of stdlib show its decision order:
schema = {"type": "object", "required": ["id"], "properties": {"id": {"type": "integer"}}}
def check(obj):
if not isinstance(obj, dict): return False
if any(k not in obj for k in schema["required"]): return False
return isinstance(obj.get("id"), int)
print(check({"id": 1})) # → True
print(check({"name": "x"})) # → False (missing required id)
print(check({"id": "x"})) # → False (id is not an integer)
The three cases map to three verdicts: structure (dict), existence (required), type. Real projects use the jsonschema package, and its order of checks—hence its error messages—matches.