Menu

Topic 5 of 8

Schema Validation Tests

Learn Schema Validation Tests for free with explanations, exercises, and a quick test (for API Engineer).

Published: January 21, 2026 | Updated: January 21, 2026

Why this matters

Schema validation tests ensure your API requests and responses match the contract you promised (OpenAPI/JSON Schema). This prevents breaking clients, speeds up debugging, and makes refactoring safer.

  • Catching breaking changes early (e.g., removing a required field).
  • Guaranteeing types, formats, and shapes of payloads are consistent across versions.
  • Automating checks in CI to block unsafe deploys.

Concept explained simply

A schema is a contract that describes what valid data looks like: which fields exist, their types, required/optional nature, formats, and allowed values. Schema validation tests verify real payloads against that contract.

  • Request validation: Reject bad inputs early (return 400 with clear errors).
  • Response validation: Ensure your service returns exactly what clients expect.

Mental model

Think of the schema as guardrails on a highway. Your payloads are the cars. If a car tries to leave the lane (wrong type, missing field), the guardrail stops it. Tests regularly drive sample cars to prove the guardrails are in the right place.

What to validate

  • Types (string, number, boolean, integer, object, array).
  • Required fields vs optional fields.
  • Nullability (optional ≠ nullable). Optional means the field may not exist; nullable means it exists but can be null.
  • Formats (email, uuid, uri, date-time) when applicable.
  • Enums and constraints (minLength, maxLength, minimum, maximum, pattern).
  • Objects: properties and whether additionalProperties are allowed.
  • Arrays: item schema, minItems, maxItems, uniqueItems.
  • Combinators: oneOf, anyOf, allOf, not if your domain needs them.
  • Response metadata: HTTP status code matches scenario, and Content-Type is correct.

Worked examples

Example 1 — Response validation for a User object

Goal: Ensure GET /users/123 returns a valid user.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "User",
  "type": "object",
  "additionalProperties": false,
  "required": ["id", "email", "createdAt"],
  "properties": {
    "id": {"type": "string", "format": "uuid"},
    "email": {"type": "string", "format": "email"},
    "name": {"type": "string", "minLength": 1},
    "createdAt": {"type": "string", "format": "date-time"},
    "roles": {
      "type": "array",
      "items": {"type": "string", "enum": ["user", "admin"]},
      "minItems": 1
    }
  }
}
  1. Call the endpoint, parse JSON.
  2. Validate against the schema. Expect pass when data is valid.
  3. Try a negative case: remove email or add an unknown field debug. Expect validation failure.

Why it works: We assert type, format, required fields, and forbid unexpected fields.

Example 2 — Request validation for Create Order (negative test)

Goal: Ensure invalid inputs are rejected with 400.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "CreateOrderRequest",
  "type": "object",
  "additionalProperties": false,
  "required": ["items", "currency"],
  "properties": {
    "items": {
      "type": "array",
      "minItems": 1,
      "items": {
        "type": "object",
        "additionalProperties": false,
        "required": ["sku", "qty"],
        "properties": {
          "sku": {"type": "string", "minLength": 1},
          "qty": {"type": "integer", "minimum": 1}
        }
      }
    },
    "currency": {"type": "string", "enum": ["USD", "EUR"]},
    "note": {"type": ["string", "null"], "maxLength": 200}
  }
}
  1. Send a request with qty: 0 → expect 400.
  2. Send a request with extra field discountCode → expect 400 if not allowed.
  3. Send a valid request → expect 201 and response schema match.
Example 3 — Strictness with additionalProperties

Goal: Prevent accidental leakage of internal fields.

{
  "type": "object",
  "additionalProperties": false,
  "required": ["id"],
  "properties": {
    "id": {"type": "string"}
  }
}

Test: Response contains id and internal debugTraceId. Validation fails because debugTraceId is not allowed. Remove or explicitly model it if needed.

How to write effective schema tests

  1. Capture the source of truth (OpenAPI/JSON Schema) close to code and version-control it.
  2. Write positive tests for each endpoint and status code you support.
  3. Write negative tests for common invalid inputs (missing required, wrong type, extra fields, bad formats).
  4. Include strictness rules where needed (additionalProperties false for public responses).
  5. Automate in CI: validate on pull requests and block if schemas or payloads break.
  6. Monitor compatibility: adding fields is usually safe; removing/renaming is not.

Tools and setup (pick what matches your stack)

  • Schema languages: JSON Schema, OpenAPI (uses JSON Schema for payloads).
  • Validators (examples): Ajv, Joi/Zod (Node), Pydantic (Python), JSON::Schema (Ruby), class-validator (TS), or built-in framework validators.
  • Test runners: Use your normal unit/integration test runner and call validators as assertions.

Tip: Keep example payloads as fixtures to make tests readable and reusable.

Exercises

Complete the exercise below. You can solve it in any language; focus on writing a clear schema and tests.

Exercise 1 (matches the track exercises)

Create a Product schema and validate both a passing and a failing payload.

  • Product fields: id (uuid string), name (non-empty string), price (number ≥ 0), tags (array of unique non-empty strings, optional), available (boolean, default true if omitted), no extra fields.
  • Positive case: valid product passes validation.
  • Negative case: price = -1 should fail with a clear message.
Checklist
  • Schema has additionalProperties set appropriately.
  • All required fields are listed.
  • Constraints: minLength, minimum, uniqueItems for tags.
  • Tests include both pass and fail cases.

Common mistakes and how to self-check

  • Confusing optional vs nullable.
    • Self-check: If a field may be absent, do not include it in required. If it may be null, include "type": ["string", "null"] (or framework equivalent).
  • Allowing silent drift by leaving additionalProperties at default (true).
    • Self-check: For public responses, consider additionalProperties: false unless you intentionally allow extension fields.
  • Missing negative tests.
    • Self-check: For each required field and format, have at least one invalid example.
  • Not validating all status codes.
    • Self-check: Validate 4xx/5xx bodies if your API documents them, or assert absence when not expected.
  • Breaking compatibility by renaming/removing fields.
    • Self-check: Run contract tests on existing fixtures from previous versions before releasing.

Practical projects

  • Harden one endpoint: Add response schemas with strict additionalProperties: false, plus request validation for all write operations.
  • Compatibility gate: Store a set of canonical example responses (golden files) and assert they continue to validate after code changes.
  • Error model: Define and validate a consistent error schema (code, message, details) across all 4xx responses.

Who this is for

  • API Engineers and Backend Developers who maintain public or internal APIs.
  • QA/SET engineers adding contract tests to CI.
  • Team leads aiming for safer refactors and clearer API contracts.

Prerequisites

  • Basic JSON and HTTP knowledge (status codes, headers, bodies).
  • Familiarity with a test runner in your language.
  • Light experience reading OpenAPI or JSON Schema helps but is not required.

Learning path

  1. Learn JSON Schema fundamentals (types, required, arrays, formats).
  2. Model your API requests and responses with schemas.
  3. Add positive and negative tests for each endpoint and status code.
  4. Enable strictness where needed and run tests in CI.
  5. Introduce versioned contracts and golden test fixtures to guard compatibility.

Next steps

  • Apply schemas to your most-used endpoint today.
  • Extend to all critical endpoints and wire into CI.
  • Schedule a periodic review to remove unused fields and document deprecations safely.

Quick Test

Take the quick test below to check your understanding. Everyone can take it. Only logged-in users get their progress saved.

Mini challenge

Pick one endpoint and add two negative tests: one for a wrong type and one for an extra unexpected property. Make both fail now, then fix the code or schema so they pass.

Practice Exercises

1 exercises to complete

Instructions

Write a JSON Schema for a Product and validate two payloads.

  1. Fields: id (uuid string), name (non-empty string), price (number ≥ 0), tags (optional array of unique non-empty strings), available (boolean, optional, default true if omitted). Forbid extra fields.
  2. Create a valid product and assert validation passes.
  3. Create an invalid product with price: -1 and assert validation fails with a clear message.
Expected Output
Validation passes for the valid product. Validation fails for the invalid product with an error indicating price must be >= 0.

Schema Validation Tests — Quick Test

Test your knowledge with 8 questions. Pass with 70% or higher.

8 questions70% to pass

Have questions about Schema Validation Tests?

AI Assistant

Ask questions about this tool