JSON Schema Validation Patterns: Types, Conditionals, Arrays, and API Payloads
jsonjson-schemaapivalidationbackenddata-contracts

JSON Schema Validation Patterns: Types, Conditionals, Arrays, and API Payloads

UUnbound Dev Editorial
2026-11-15
8 min read

A practical JSON Schema validation checklist covering types, required fields, arrays, conditionals, formats, drafts, and API payload debugging.

JSON Schema validation turns informal API expectations into executable rules. This practical checklist shows how to validate types, required properties, nested objects, arrays, formats, conditionals, and reusable definitions, then apply those patterns to request payloads, responses, and form data.

Overview

A JSON Schema describes the shape and constraints of JSON data. A validator compares an instance—the JSON document being checked—with that schema and returns either a valid result or one or more validation errors. The schema does not transform data, authenticate a user, or replace business logic. It provides a consistent contract at a boundary such as an HTTP request, message queue, configuration file, or form submission.

Start with the smallest useful contract. Define the expected top-level type, identify required fields, constrain values that have a known vocabulary, and add nested rules only where they protect a real assumption. Overly permissive schemas allow malformed data through; overly strict schemas can make harmless changes unnecessarily difficult.

A basic API request schema might look like this:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "CreateUserRequest",
  "type": "object",
  "required": ["email", "displayName"],
  "properties": {
    "email": {
      "type": "string",
      "format": "email"
    },
    "displayName": {
      "type": "string",
      "minLength": 1
    },
    "role": {
      "type": "string",
      "enum": ["member", "admin"]
    }
  },
  "additionalProperties": false
}

Here, required controls presence, while properties controls the rules for fields that are present. A property listed in properties is not automatically required. That distinction is one of the most common sources of unexpected validation results.

Checklist by scenario

When validating primitive values

  • Set type explicitly: string, number, integer, boolean, null, object, or array.
  • Use minimum, maximum, and their exclusive variants for numeric boundaries.
  • Use minLength, maxLength, and pattern for strings when the constraint is part of the data contract.
  • Use enum for a closed list of values and const when exactly one value is allowed.

Remember that JSON distinguishes numbers, strings, booleans, objects, arrays, and null. A value such as "42" is a string, not a number. A validator normally reports that mismatch rather than converting it. If an API accepts both forms, model that decision deliberately with composition such as anyOf, or normalize the input before validation.

When validating objects and API payloads

  • Use type: object at the relevant level.
  • List mandatory fields in required.
  • Define field rules under properties.
  • Use additionalProperties: false only when unknown fields should be rejected.
  • Use minProperties or maxProperties when the number of fields matters.

For public or frequently evolving APIs, consider whether rejecting every unknown property is compatible with forward compatibility. A strict schema can catch misspellings early, but clients may fail when a server adds a field or when metadata is legitimately extensible. An alternative is to allow additional properties while explicitly validating the fields your application consumes.

When validating arrays

  • Set type: array and define item rules with items.
  • Use minItems and maxItems for collection size.
  • Use uniqueItems: true when duplicate values are invalid.
  • Use contains when at least one item must satisfy a separate rule.
{
  "type": "object",
  "required": ["items"],
  "properties": {
    "items": {
      "type": "array",
      "minItems": 1,
      "items": {
        "type": "object",
        "required": ["sku", "quantity"],
        "properties": {
          "sku": { "type": "string", "minLength": 1 },
          "quantity": { "type": "integer", "minimum": 1 }
        },
        "additionalProperties": false
      }
    }
  }
}

When validating conditional payloads

Use if, then, and else when one field changes the requirements for another. For example, a delivery address may be required only when the order method is shipping:

{
  "type": "object",
  "required": ["fulfillmentMethod"],
  "properties": {
    "fulfillmentMethod": {
      "type": "string",
      "enum": ["pickup", "shipping"]
    },
    "address": {
      "type": "object",
      "required": ["line1", "postalCode"],
      "properties": {
        "line1": { "type": "string" },
        "postalCode": { "type": "string" }
      }
    }
  },
  "if": {
    "properties": { "fulfillmentMethod": { "const": "shipping" } },
    "required": ["fulfillmentMethod"]
  },
  "then": { "required": ["address"] },
  "else": { "not": { "required": ["address"] } }
}

Including the conditional field in the if schema's required list matters. Without it, an object that omits fulfillmentMethod may still satisfy the properties subschema because absent properties do not fail that subschema by themselves.

When reusing definitions

Put shared structures in $defs and reference them with $ref. This is useful for identifiers, pagination objects, addresses, and error responses.

{
  "$defs": {
    "uuid": {
      "type": "string",
      "pattern": "^[0-9a-fA-F-]{36}$"
    }
  },
  "type": "object",
  "required": ["id"],
  "properties": {
    "id": { "$ref": "#/$defs/uuid" }
  }
}

A pattern such as this is only a structural check, not proof that an identifier exists or is registered. Keep database and service-level checks outside the JSON Schema.

Draft versions and validator behavior

Choose a draft intentionally and configure every validator in the toolchain to use the same dialect. The $schema value identifies the intended vocabulary, but support still depends on the validator and its configuration.

Schema familyPractical considerationChecklist
Draft-04Common in older integrations and examples.Confirm older keyword and reference behavior before copying a newer schema into a legacy validator.
Draft-06 and Draft-07Widely encountered in established API tooling.Check which conditional, reference, and vocabulary features the selected validator supports.
2019-09Introduces later vocabulary and reusable-schema patterns.Set the dialect explicitly and test references across files or document boundaries.
2020-12Uses the current style of vocabularies and $defs.Verify that your API gateway, test runner, code generator, and editor all support the same features.

Do not treat a schema as portable merely because it is valid JSON. A validator may ignore an unsupported keyword, reject it, or apply different defaults. Test the exact library or platform used in production, not only an online validator. For API request troubleshooting, pair schema validation with a reproducible request; the curl REST API examples guide can help isolate headers, methods, and JSON-body issues.

What to double-check

Formats are not always assertions

Keywords such as format: email, date-time, uri, and ipv4 describe specialized string formats. Whether a validator treats them as an error, warning, or annotation can depend on configuration. Confirm format enforcement explicitly, especially when accepting security-sensitive URLs, timestamps, or account identifiers. A format check also does not prove that an email can receive mail or that a URL is reachable.

Composition changes the error picture

allOf requires every subschema to pass; anyOf requires at least one; oneOf requires exactly one; and not rejects instances that match its subschema. Use discriminating fields when possible. Two overlapping branches in oneOf can cause a valid-looking payload to fail because it matches both branches.

Requests and responses need separate contracts

A create request may require fields that a response adds automatically, such as an identifier or timestamp. Maintain separate request and response schemas or compose them carefully. For partial updates, a PATCH schema usually differs from a create schema because fields may be optional while still being constrained when present.

Validation is not business authorization

A schema can require a role to be one of a known set, but it cannot decide whether the current caller may assign that role. It can constrain a number, but it cannot establish whether inventory is available. Use schema validation as the first boundary, followed by authentication, authorization, persistence, and domain validation.

Common mistakes

  • Assuming properties are required: Add the field name to required; defining it under properties alone is not enough.
  • Using the wrong numeric type: integer and number are not interchangeable in every contract.
  • Expecting coercion: A validator generally checks the supplied JSON rather than converting strings into numbers or booleans.
  • Making every object closed: additionalProperties: false can reject harmless metadata or future fields. Apply it where strictness is intentional.
  • Writing a fragile regex: Patterns are easy to overconstrain. Test representative valid and invalid values, including boundary cases.
  • Ignoring array nesting: Put item rules inside items; rules on the array itself do not automatically apply to each element.
  • Mixing drafts: A schema copied from one draft may contain keywords or reference behavior that another validator does not implement.
  • Reading only the first error: Inspect the instance path, keyword, and surrounding object. Several errors may be consequences of one incorrect shape.

When debugging, first validate that the payload is syntactically valid JSON. Then check the top-level type, the path named by the error, required fields, and the schema dialect. A JSON formatter or the broader online developer utilities comparison can help make deeply nested data easier to inspect, but formatting does not validate semantics.

When to revisit

Revisit a JSON Schema whenever the API contract changes, a new client is introduced, or a rejected payload reveals an unclear assumption. Before deployment, compare the old and new schemas and decide whether each change is additive, narrowing, or potentially breaking. Test representative fixtures for valid requests, missing fields, wrong types, boundary values, unknown properties, and conditional branches.

Also review schemas when upgrading a validator, changing an API gateway, moving between draft versions, or enabling format assertions. Confirm that local tests, CI, generated documentation, client code, and production validation use the same dialect and options. If schemas are stored in CI or deployment configuration, review them alongside the related configuration; the YAML validator guide is useful when the schema is embedded in a larger workflow file.

Use this final release checklist:

  1. Declare the intended schema draft with $schema.
  2. Validate the top-level JSON type and every required field.
  3. Test nested objects, arrays, enums, boundaries, and conditional branches.
  4. Decide explicitly whether unknown properties are accepted.
  5. Confirm format enforcement rather than assuming it.
  6. Run the schema through the same validator and configuration used by the API.
  7. Keep business rules, authorization, and external lookups in application logic.
  8. Record fixtures for both successful and intentionally rejected payloads.

A schema is most valuable when it remains close to the code and tests that enforce it. Treat it as a maintained API contract: precise enough to catch bad data, flexible enough to evolve, and explicit about the assumptions that downstream systems actually depend on.

Related Topics

#json#json-schema#api#validation#backend#data-contracts
U

Unbound Dev Editorial

Developer Resources Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.