All articles
165 articles · updated weekly See our Tools
All articles
Tutorials

JSON Schema for REST APIs: The Design Decisions That Make the Contract Work

How to write a JSON Schema that validates a REST API payload: a payment example with enums, arrays, $ref and money values, explained decision by decision.

JSON Schema for REST APIs: The Design Decisions That Make the Contract Work
COVER · Tutorials

The first JSON Schema I wrote for a payment endpoint passed code review, passed the tests, and rejected a perfectly valid 19.99 order in production. The amount was fine; the problem was "multipleOf": 0.01 on a number field, validated in JavaScript with floating point. That is the kind of decision no syntax tutorial covers, and it decides whether the schema becomes a trusted contract or an obstacle someone works around with additionalProperties: true.

This post builds a complete JSON Schema example for a REST API payload, POST /payments, decision by decision, in draft 2020-12 (the same dialect OpenAPI 3.1 uses), and runs all of it in Ajv. If you are still at the concept of validating shape and not just syntax, start with schema validation for JSON; if you want the introduction with Node and Python implementations, it is in JSON Schema in practice.

The payload: POST /payments

The endpoint creates a payment. The expected body:

{
  "amount_cents": 15000,
  "currency": "BRL",
  "payment_method": "pix",
  "customer": {
    "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
    "email": "customer@example.com"
  },
  "items": [
    { "product_id": "prod_123", "quantity": 2, "unit_price_cents": 7500 }
  ],
  "metadata": { "order_ref": "ORD-2026-001" }
}

Note that the amount is already in integer cents (15000 for 150.00). That is the first decision in this post, and the numbers that justify it come further down.

Which $schema to use: draft-07 or 2020-12

The first line of the schema declares the dialect, and it has to be exact, because the validator uses that URI as the key to find the meta-schema. The official identifiers are:

  • draft-07: http://json-schema.org/draft-07/schema# (with http, and with a trailing #)
  • 2020-12: https://json-schema.org/draft/2020-12/schema (with https, no #)

Swapping draft-07's http for https looks harmless and breaks compilation. I tested it in Ajv 8.20 with new Ajv():

draft-07 with https  -> no schema with key or ref "https://json-schema.org/draft-07/schema#"
draft-07 with http   -> OK
2020-12 in new Ajv() -> no schema with key or ref "https://json-schema.org/draft/2020-12/schema"
2020-12 in Ajv2020   -> OK

The last line is the other trap: the default Ajv class is draft-07. For 2020-12 you import the Ajv2020 class from ajv/dist/2020.

I pick 2020-12 for a new API for a practical reason: OpenAPI 3.1 defines the Schema Object as a superset of JSON Schema draft 2020-12 (3.2, from September 2025, keeps that). The same schema validates the payload on the server and describes the contract in the docs. In OpenAPI 3.0, the Schema Object was an "extended subset" of an older draft, with differences that forced you to maintain two versions.

The root level: required and additionalProperties: false

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://api.example.com/schemas/create-payment.json",
  "type": "object",
  "properties": { "...": "filled in over the next sections" },
  "required": ["amount_cents", "currency", "payment_method", "customer", "items"],
  "additionalProperties": false
}

metadata stays out of required: it is optional. And additionalProperties: false rejects any undeclared field. In a payment API that is defense, not pedantry: without that line, a client sends "coupon": "BLACKFRIDAY", the schema silently accepts it, and the field either vanishes along the way or, worse, reaches an ORM that saves whatever arrives. The nuances of required (a field present as null, required without type, nested objects) are in JSON Schema required; here the point is just the defensive combination.

The $id gives the schema a stable identity. It becomes the base for resolving $ref, and it is what you use to register the schema in the validator and reference it from the OpenAPI spec.

Money: why multipleOf: 0.01 fails and what to use instead

The "obvious" version of the amount field:

"amount": { "type": "number", "minimum": 0.01, "multipleOf": 0.01 }

The intent is "at most two decimal places." The problem is that JavaScript validators check multipleOf by dividing one double by another, and 0.01 has no exact binary representation. I ran it in Ajv 8.20:

150    -> valid
1.1    -> valid
19.99  -> INVALID
4.35   -> INVALID
0.29   -> INVALID
8.2    -> INVALID
4.35 / 0.01 = 434.99999999999994

Legitimate values rejected at random. Ajv has an option made for this, multipleOfPrecision, which replaces the check with |round(x/d) - x/d| < 10^-N. With multipleOfPrecision: 9, 19.99, 4.35 and 0.29 pass and 10.123 is still rejected. But it only moves the problem: in the same test, 1234567.89 came back invalid, because the rounding error of the division (about 1.5 × 10^-8) already exceeds the tolerance. In other words, the fix works for small values and fails precisely on the large ones.

The solution I use, and recommend as the default for any API that handles money, is cents as an integer:

"amount_cents": { "type": "integer", "minimum": 1, "maximum": 100000000 }

No floating point, no multipleOf, no validator option. "type": "integer" rejects 150.5, minimum: 1 rejects zero and negatives, and the maximum is a sanity ceiling (1 million here; adjust to your rules). The _cents suffix in the name prevents the most expensive ambiguity of all: someone sending whole currency units into a cents field. The difference between number and integer, and the "must be integer" error, are broken down in JSON Schema type errors.

If the contract already exists with decimals and you can't change it, the honest alternatives are: a string with a pattern ("^\\d+\\.\\d{2}$"), or a number without multipleOf and the decimal-places check done in code with a decimal type. What you can't do is trust multipleOf: 0.01 with floats.

Enums, nested objects and $defs

currency and payment_method are closed lists, so enum:

"currency": { "enum": ["BRL", "USD", "EUR"] },
"payment_method": { "enum": ["credit_card", "debit_card", "pix", "boleto"] }

When every enum value is a string, "type": "string" is redundant; keeping it or not is a readability call.

customer and each item are objects with their own rules. Since Customer shows up in other endpoints (refunds, subscriptions), it goes into $defs and is referenced with $ref. In 2020-12 the place is $defs; definitions was the draft-07 name and still works for compatibility, but it is no longer the standard.

"$defs": {
  "Customer": {
    "type": "object",
    "properties": {
      "id": { "type": "string", "format": "uuid" },
      "email": { "type": "string", "format": "email", "maxLength": 254 }
    },
    "required": ["id", "email"],
    "additionalProperties": false
  },
  "Item": {
    "type": "object",
    "properties": {
      "product_id": { "type": "string", "minLength": 1, "maxLength": 64 },
      "quantity": { "type": "integer", "minimum": 1 },
      "unit_price_cents": { "type": "integer", "minimum": 0 }
    },
    "required": ["product_id", "quantity", "unit_price_cents"],
    "additionalProperties": false
  }
}

Each level has its own required and its own additionalProperties; nothing propagates from the root into customer. On the array, minItems: 1 rejects a payment with no items and maxItems: 100 caps the payload size. The maxLength values look like a detail, but in a public API every string without a ceiling is an invitation to send 5 MB in an ID field.

metadata uses additionalProperties with a schema instead of false: it accepts any key, as long as the value is a short string.

"metadata": {
  "type": "object",
  "maxProperties": 10,
  "propertyNames": { "maxLength": 40 },
  "additionalProperties": { "type": "string", "maxLength": 500 }
}

format in Ajv: addFormats, not formats: true

"format": "uuid" and "format": "email" are not validated by Ajv's core. Formats come from the ajv-formats package, registered with addFormats(ajv). Plenty of material tells you to pass { formats: true } to the constructor; in Ajv v8 that enables nothing (the formats option expects an object of format definitions). I tested the three scenarios:

no ajv-formats (default strict)  -> compile error: unknown format "uuid" ignored in schema at path "#"
no ajv-formats, strict: false    -> compiles with a console warning, and "xyz" passes as a uuid
new Ajv2020({ formats: true })   -> the same error: unknown format "uuid"

Note the default behavior: Ajv v8 doesn't silently ignore the format, it fails to compile. The silence only happens if someone turned strict mode off, and then any string passes as a UUID. The correct setup:

import Ajv2020 from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
import schema from "./create-payment.json" with { type: "json" };

const ajv = new Ajv2020({ allErrors: true });
addFormats(ajv);
export const validateCreatePayment = ajv.compile(schema);

Compile once, at application startup, and reuse the function; compiling on every request is a classic Ajv performance mistake, and Ajv's own docs tell you to compile once and reuse. allErrors: true returns every problem at once instead of stopping at the first one, which the integrator will appreciate.

The complete schema and the test

Putting the sections together:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://api.example.com/schemas/create-payment.json",
  "title": "CreatePaymentRequest",
  "type": "object",
  "properties": {
    "amount_cents": { "type": "integer", "minimum": 1, "maximum": 100000000 },
    "currency": { "enum": ["BRL", "USD", "EUR"] },
    "payment_method": { "enum": ["credit_card", "debit_card", "pix", "boleto"] },
    "customer": { "$ref": "#/$defs/Customer" },
    "items": {
      "type": "array",
      "minItems": 1,
      "maxItems": 100,
      "items": { "$ref": "#/$defs/Item" }
    },
    "metadata": {
      "type": "object",
      "maxProperties": 10,
      "propertyNames": { "maxLength": 40 },
      "additionalProperties": { "type": "string", "maxLength": 500 }
    }
  },
  "required": ["amount_cents", "currency", "payment_method", "customer", "items"],
  "additionalProperties": false,
  "$defs": {
    "Customer": {
      "type": "object",
      "properties": {
        "id": { "type": "string", "format": "uuid" },
        "email": { "type": "string", "format": "email", "maxLength": 254 }
      },
      "required": ["id", "email"],
      "additionalProperties": false
    },
    "Item": {
      "type": "object",
      "properties": {
        "product_id": { "type": "string", "minLength": 1, "maxLength": 64 },
        "quantity": { "type": "integer", "minimum": 1 },
        "unit_price_cents": { "type": "integer", "minimum": 0 }
      },
      "required": ["product_id", "quantity", "unit_price_cents"],
      "additionalProperties": false
    }
  }
}

The payload from the start passes. This one, with six problems, returns all six at once (real output from Ajv 8.20 with ajv-formats 3.0.1):

{
  "amount_cents": 150.5,
  "currency": "BRL",
  "payment_method": "crypto",
  "customer": { "id": "123", "email": "customer@example" },
  "items": [],
  "coupon": "BLACKFRIDAY"
}
/                must NOT have additional properties (coupon)
/amount_cents    must be integer
/payment_method  must be equal to one of the allowed values
/customer/id     must match format "uuid"
/customer/email  must match format "email"
/items           must NOT have fewer than 1 items

Each error's instancePath is already a JSON Pointer, so you can return it to the client in Problem Details format (RFC 9457), with a pointer per field, without translating anything:

function toProblem(errors) {
  return {
    type: "https://api.example.com/problems/validation-error",
    title: "Invalid payload",
    status: 400,
    errors: errors.map((e) => ({ pointer: "#" + e.instancePath, detail: e.message })),
  };
}

Which status to use (400 or 422) and the full error body format are in the REST API best practices post; what matters is that the whole API uses the same one.

One thing this schema does not do: check that amount_cents equals the sum of quantity × unit_price_cents. JSON Schema validates shape, not business rules across fields. That stays in code, after validation.

How the schema evolves: request and response don't break the same way

The rule everyone memorizes ("widening is compatible, narrowing is breaking") only holds for half the contract. It depends on who produces and who consumes the data.

In the request schema (the client sends, the server validates): adding an optional field, widening an enum or relaxing a minimum is compatible, because everything that was accepted still is. Adding a field to required, removing an enum value or tightening a limit breaks existing clients.

In the response schema (the server sends, the client consumes): the logic flips. Adding "refunded" to the status enum looks harmless, but it breaks the client that wrote an exhaustive switch or generated a closed type from the schema; the new value lands in a case that doesn't exist. In the response, removing a field is breaking and widening an enum can be too. So: document that clients must tolerate unknown fields and values, and treat a new response enum value as a change that needs notice.

The response schema, by the way, is a separate document: it has id, status and created_at ("format": "date-time"), which the client receives but never sends. Don't try to reuse the request schema with optional fields; they are different contracts.

Frequently asked questions

Should I use draft-07 or 2020-12 for a new API?

2020-12, especially if you document with OpenAPI 3.1 or 3.2, which use that dialect in the Schema Object. Draft-07 is still well supported and reasonable to keep in a project that already uses it; just check that $schema uses http:// and the trailing #, and don't mix definitions and $defs in the same schema.

Why does Ajv say "no schema with key or ref" for $schema?

Because the $schema URI doesn't match any meta-schema registered in that instance. The two common causes: draft-07 written with https (the official identifier is http), or a 2020-12 schema compiled with the default Ajv instead of Ajv2020.

Does additionalProperties: false get in the way of API evolution?

On the request, no: the server owns the schema and adds the new field to properties when it starts accepting it. It gets in the way when used on the client side to validate responses, because then any new server field becomes an error. Use false on what you receive, and tolerance on what you consume.

How should I store money in JSON Schema?

In cents, as an integer, with a minimum and a sanity maximum. A number with multipleOf: 0.01 rejects valid values like 19.99 in JavaScript validators, and Ajv's multipleOfPrecision option only fixes some of the cases.

The schema is the contract, so test the schema

A good API JSON Schema isn't the one that declares every field; it is the one that makes explicit decisions: an exact dialect in $schema, additionalProperties: false on what comes in, money as an integer, format with the plugin actually loaded, and ceilings on every string and array. And, as the 19.99 case showed, it has to be tested with real and edge-case values before it reaches production, just like any other code. If you can generate the client's type from the same schema, even better: the contract gets a single source.

The editorial content ends here. To test the schema against edge-case payloads without starting the app, I paste both into the Quick Tools JSON Schema validator, which shows the exact path of each failure; to generate the TypeScript interface for the same payload, the JSON to TypeScript converter.

RD
Author
Rafael Duarte
Backend developer with a background in fintech and B2B SaaS — worked on teams that scaled APIs from zero to millions of requests. Carries enough production scars to hold strong opinions on tools, patterns and architecture decisions. Not an academic: he read the UUID RFC when he had to choose between v4 and v7 for a write-heavy table.
View profile