Schema Validation

API Testing

// Definition

Asserting that an API request or response matches a defined schema (JSON Schema, OpenAPI, Protobuf). Catches contract drift the moment it appears, without writing field-by-field assertions in every test.

// Code Example

CypressValidate a response against a JSON schema
TypeScript
import Ajv from 'ajv';

const schema = {
  type: 'object',
  required: ['id', 'name'],
  properties: {
    id: { type: 'string' },
    name: { type: 'string' },
  },
};

cy.request('/api/tools/cypress').then((res) => {
  const valid = new Ajv().validate(schema, res.body);
  expect(valid, 'response matches schema').to.be.true;
});

// Related terms

Learn more · API Testing Masterclass

Chapter 5 · Lesson 2: JSON Schema Validation