Skip to content
SDETRole
SDETRole

Glossary · API testing

JSON Schema

Also called: JSON Schemas, JSON schema validation, schema validation

Definition

A JSON vocabulary for describing the expected structure of JSON data, including types, required fields and formats, used to validate API responses.

JSON Schema is a standard way to describe what a valid JSON document looks like: which properties exist, their types, which are required, allowed values and formats. A validator then checks real data against the schema and reports every violation. For API testers it turns “the response looks right” into a single, repeatable check of the whole response shape. The current version of the specification is draft 2020-12; draft-07 is still very widely used.

Example

A schema for a user returned by GET /users/{id}:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["id", "email", "role", "createdAt"],
  "properties": {
    "id": { "type": "integer", "minimum": 1 },
    "email": { "type": "string", "format": "email" },
    "role": { "enum": ["admin", "member", "viewer"] },
    "createdAt": { "type": "string", "format": "date-time" },
    "nickname": { "type": ["string", "null"] }
  },
  "additionalProperties": false
}

Validating in Node with Ajv (ajv/dist/2020 supports draft 2020-12, and ajv-formats adds email and date-time):

import Ajv2020 from 'ajv/dist/2020';
import addFormats from 'ajv-formats';

const ajv = new Ajv2020({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile(userSchema);

if (!validate(responseBody)) {
  console.log(validate.errors);
}

In Java, REST Assured’s json-schema-validator module provides matchesJsonSchemaInClasspath("schemas/user.json") for use inside .body(...). Check which draft your validator supports before using newer keywords.

Why it matters

  • One assertion covers the whole shape. Missing fields, wrong types and unexpected nulls are caught without writing a check per field.
  • It catches leaks. "additionalProperties": false fails if the response suddenly includes something like passwordHash.
  • It documents the contract. OpenAPI specifications use JSON Schema to describe request and response bodies.

Common mistakes

  • Schemas that accept anything. A schema without required passes for {}. Always list required fields.
  • Assuming format is enforced. Many validators treat format as an annotation unless format validation is switched on.
  • Validating only the schema. A response can match the schema and still contain the wrong user. Keep value assertions for the data that matters.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →