Try it yourself with our free Json Validator tool — runs entirely in your browser, no signup needed.

How to Validate JSON for API Responses

How to Validate JSON for API Responses

Validating JSON data is crucial when working with API responses to ensure that the data received is correct, consistent, and can be processed without errors. In this article, we will explore how to validate JSON data for API responses, covering common scenarios, best practices, and common mistakes to avoid.

Quick Example

Here is a minimal example of how to validate JSON data using the popular ajv library in JavaScript:

import Ajv from 'ajv';

const ajv = new Ajv();
const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'integer' }
  },
  required: ['name', 'age']
};

const jsonData = { name: 'John Doe', age: 30 };

const valid = ajv.validate(schema, jsonData);
if (!valid) {
  console.log(ajv.errors);
} else {
  console.log('JSON data is valid');
}

To use this example, install ajv using npm install ajv or yarn add ajv.

Real-World Scenarios

Scenario 1: Validating User Data

When creating a new user, you want to ensure that the API response contains the required fields and that the data types are correct.

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

const userData = {
  id: 1,
  name: 'John Doe',
  email: 'johndoe@example.com'
};

const valid = ajv.validate(schema, userData);
if (!valid) {
  console.log(ajv.errors);
} else {
  console.log('User data is valid');
}

Scenario 2: Validating Paginated Data

When retrieving a list of items, you want to ensure that the API response contains the required metadata and that the data is paginated correctly.

const schema = {
  type: 'object',
  properties: {
    data: { type: 'array', items: { type: 'object' } },
    meta: {
      type: 'object',
      properties: {
        currentPage: { type: 'integer' },
        totalPages: { type: 'integer' },
        itemCount: { type: 'integer' }
      },
      required: ['currentPage', 'totalPages', 'itemCount']
    }
  },
  required: ['data', 'meta']
};

const paginatedData = {
  data: [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }],
  meta: {
    currentPage: 1,
    totalPages: 5,
    itemCount: 10
  }
};

const valid = ajv.validate(schema, paginatedData);
if (!valid) {
  console.log(ajv.errors);
} else {
  console.log('Paginated data is valid');
}

Scenario 3: Validating Error Responses

When handling errors, you want to ensure that the API response contains the required error information and that the data types are correct.

const schema = {
  type: 'object',
  properties: {
    error: { type: 'string' },
    code: { type: 'integer' },
    message: { type: 'string' }
  },
  required: ['error', 'code', 'message']
};

const errorData = {
  error: 'Invalid request',
  code: 400,
  message: 'Invalid request parameters'
};

const valid = ajv.validate(schema, errorData);
if (!valid) {
  console.log(ajv.errors);
} else {
  console.log('Error data is valid');
}

Best Practices

  1. Use a validation library: Instead of writing custom validation logic, use a well-maintained library like ajv to handle JSON validation.
  2. Define a clear schema: Define a clear and concise schema for your API responses to ensure that the data is consistent and correct.
  3. Use required fields: Use required fields to ensure that the API response contains the necessary data.
  4. Handle errors: Handle validation errors correctly and provide meaningful error messages to the user.
  5. Test thoroughly: Test your validation logic thoroughly to ensure that it works correctly in different scenarios.

Common Mistakes

Mistake 1: Not using a validation library

// Wrong
function validateData(data) {
  if (typeof data !== 'object') {
    return false;
  }
  // ...
}

// Correct
import Ajv from 'ajv';
const ajv = new Ajv();
const schema = { /* ... */ };
const valid = ajv.validate(schema, data);

Mistake 2: Not defining a clear schema

// Wrong
const schema = {
  type: 'object'
};

// Correct
const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'integer' }
  },
  required: ['name', 'age']
};

Mistake 3: Not handling errors correctly

// Wrong
if (!valid) {
  console.log('Invalid data');
}

// Correct
if (!valid) {
  console.log(ajv.errors);
  // Handle error accordingly
}

FAQ

Q: What is the difference between ajv and other validation libraries?

A: ajv is a fast and lightweight JSON validation library that supports JSON Schema draft-07 and has a simple and intuitive API.

Q: Can I use ajv with TypeScript?

A: Yes, ajv is compatible with TypeScript and provides type definitions for TypeScript projects.

Q: How do I handle validation errors?

A: You can handle validation errors by checking the errors property of the ajv instance and providing meaningful error messages to the user.

Q: Can I use ajv with other data formats?

A: No, ajv is specifically designed for JSON validation and does not support other data formats.

Q: Is ajv secure?

A: Yes, ajv is designed to be secure and follows best practices for secure coding.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp