QA Interview Hub · Knowledge base · Quizzes · Українська

API › Documentation and contracts: OpenAPI, JSON Schema, contract testing

Schema validation in code: ajv and zod

Responses are checked against a schema in code: ajv uses standard JSON Schema, while zod defines the schema in TypeScript and infers its type. Such a check catches wrong types that a field-exists check misses, and shows the path to the violation. Responses that must be exact need strict mode (additionalProperties: false or z.strictObject), because extra fields otherwise pass, and a schema checks shape, not values.

API · Contracts

The test checks that amount exists and lets the string "150" through. What should check the structure?

The response of /v1/transfers/tr_91 contains "amount": "150" (a string), and the test is expect(body.amount).toBeDefined(). The test is green. A month later the mobile app crashes because it adds a number to the amount. "The field exists" said nothing about type, and a schema closes that gap.

The lesson covers two tools used to validate responses in TypeScript: ajv (JSON Schema) and zod (schemas as code), how they differ and where the blind spot remains.

How it works

A schema describes the shape of data: which fields, of which types, which are required, what is allowed. A validator takes a response and a schema and returns "yes" or a list of violations with paths to the problem fields. The test then does not check fields one by one but demands "the response matches the contract". The error shows exactly what is wrong.

ajv reads standard JSON Schema. If the schema already exists in OpenAPI (3.1, where a schema is JSON Schema 2020-12), it does not have to be rewritten. zod works the other way round: the schema is written in TypeScript and the type is derived from it (z.infer). Then schema and type cannot drift, but there is no separate contract file.

ajv or zod

ajv

A JSON Schema or OpenAPI file already exists. The schema is not duplicated, it is taken from the specification. You need ajv-formats for format and careful strict settings.

zod

There is no specification or the contract is kept in code. Schema and type are in one place, error messages are readable. An OpenAPI file cannot be obtained from it.

Figure 1. Both options are legitimate: the choice depends on where the contract lives.

Example: from "the field exists" to a schema

A weak check:

const body = await res.json();
expect(body.id).toBeDefined();
expect(body.amount).toBeDefined(); // passes for "150" and for null

It lets through a string instead of a number, and null. The same with ajv, the schema taken from the specification:

import Ajv2020 from 'ajv/dist/2020';
import addFormats from 'ajv-formats';
import { readFileSync } from 'node:fs';
import { parse } from 'yaml';

const spec = parse(readFileSync('openapi.yaml', 'utf8'));
const ajv = new Ajv2020({ allErrors: true, strict: false });
addFormats(ajv);
const validateTransfer = ajv.compile({
  $ref: '#/components/schemas/Transfer',
  components: spec.components,
});

test('transfer matches the spec', async ({ request }) => {
  const body = await (await request.get('/v1/transfers/tr_91')).json();
  const ok = validateTransfer(body);
  expect(ok, JSON.stringify(validateTransfer.errors)).toBe(true);
});

What matters here. Ajv2020 is needed because OpenAPI 3.1 schemas follow JSON Schema 2020-12. strict: false allows OpenAPI-only keywords such as example or discriminator, which ajv would otherwise reject. The $ref to components works because we pass them in the schema root. Specifications 3.0 use a different dialect (nullable, boolean exclusiveMinimum), so this code does not fit them without converting the schemas.

The same in zod, when schemas live in code:

import { z } from 'zod';

const Transfer = z.strictObject({
  id: z.string(),
  status: z.enum(['pending', 'completed', 'failed']),
  amount: z.number().positive(),
  note: z.string().nullable(), // may be null, must be present
  memo: z.string().optional(), // may be absent
});

test('transfer matches the contract', async ({ request }) => {
  const body = await (await request.get('/v1/transfers/tr_91')).json();
  const parsed = Transfer.safeParse(body);
  expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
});

Note strictObject (.strict() works the same): by default zod silently drops unknown keys, and the test would let an extra field such as cardNumber through. In ajv extra fields pass too, unless the schema has additionalProperties: false:

Transfer:
  type: object
  required: [id, status, amount]
  properties:
    id: { type: string }
    status: { type: string }
    amount: { type: number }
  # additionalProperties is true by default: an extra "cardNumber" passes

This is a common source of vulnerabilities: an extra field in a response can be a data leak. So for responses that must be exact, enable the strict check.

Limits and alternatives

  • A schema checks shape, not content. amount: 150 passes even if 200 was expected. Values are checked separately.
  • format is not always enforced. In JSON Schema 2020-12 it is an annotation by default; ajv checks formats only with ajv-formats.
  • Required, optional and null are three different cases: required in a schema, an absent field and the value null. In zod these are .optional() and .nullable(), in OpenAPI 3.1 (JSON Schema 2020-12) they are required and type: [string, 'null'].
  • Postman has pm.response.to.have.jsonSchema(schema) inside a script, Playwright and Cypress have no built-in schema validation, so you plug in ajv or zod as above, and REST Assured has the json-schema-validator module (matchesJsonSchemaInClasspath) built on a separate Java library.

Typical mistakes

  • Validating only the success response. Error bodies need a schema too, otherwise the error format breaks easily.
  • One big expect(parsed.success) without a message. The test fails with "expected true" and the cause is hunted by hand. Pass JSON.stringify(parsed.error?.issues) or validate.errors.
  • Not enabling strict mode for responses. Extra fields pass silently.
  • Copying the schema into zod when OpenAPI already exists. Two sources of truth again.

Check yourself

The server started returning an extra field internalScore. The schema has no additionalProperties: false (or zod without strict). Is the test green or red?

Answer

Green: extra keys are not forbidden by the schema (zod even drops them). To notice the extra field you need strict mode: additionalProperties: false or z.strictObject.

How does .optional() differ from .nullable() in zod?

Answer

.optional() allows the field to be absent altogether, .nullable() allows the value null but the field must be present. They are different cases and a contract must tell them apart.

In an interview. Junior: In tests I validate the response with a schema: ajv for JSON Schema or zod when the schema is in TypeScript. It beats checking fields one by one because it catches wrong types. Middle/Senior: With OpenAPI 3.1 I take schemas from it through ajv (Ajv2020 and ajv-formats) so the contract is not duplicated. I enable strict checks for extra fields, tell required, optional and nullable apart and put the full validation error in the message. A schema does not replace value checks, so I write business assertions separately.

More articles in this chapter