How to Validate AI API Responses with Zod and AJV (and Avoid Breaking Your Frontend)



This content originally appeared on DEV Community and was authored by Elvis Ansima

Why Validate API Responses from AI?

Integrating AI APIs (like OpenAI, Gemini, or Claude) comes with an annoying risk—responses can be inconsistent, missing fields, or contain unexpected data that breaks your frontend.

For example:

Dev: “Return JSON with name, age, and email fields.”

AI: Returns a JSON… with nickname instead of name and no email.

💀 Frontend crashes.

👉 Solution? Validate your AI API responses before using them!

Using AJV for AI API Validation (Schema-Based Approach)

AJV is great when working with strict JSON structures.

1⃣ Install AJV

npm install ajv

2⃣ Define Your Expected AI Response Schema

const Ajv = require("ajv");
const ajv = new Ajv();

const schema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "number" },
    email: { type: "string", format: "email" }
  },
  required: ["name", "age", "email"],  // Ensure all fields exist
  additionalProperties: false  // Prevent unexpected fields
};

const validate = ajv.compile(schema);

// Simulated AI API response
const aiResponse = { name: "John Doe", age: 25 };  // Missing 'email' field

if (!validate(aiResponse)) {
  console.error("❌ Invalid AI Response:", validate.errors);
} else {
  console.log("✅ AI Response is Valid!");
}

🔹 Why use AJV?

✅ Works well for structured API responses

✅ Fast and optimized for large-scale AI integrations

✅ Enforces strict field requirements

Using Zod for AI API Validation (TypeScript-Friendly Approach)

Zod is great for AI-generated responses that may contain optional fields or dynamic structures.

1⃣ Install Zod

npm install zod

2⃣ Define Your AI Response Schema

import { z } from "zod";

const aiResponseSchema = z.object({
  name: z.string(),
  age: z.number(),
  email: z.string().email().optional(), // Allow missing email field
  metadata: z.object({  // Handling nested AI responses
    model: z.string().optional(),
    confidence: z.number().min(0).max(1).optional()
  }).optional()
});

const aiResponse = { name: "John", age: 25, metadata: { model: "GPT-4", confidence: 0.92 } };

const result = aiResponseSchema.safeParse(aiResponse);

if (!result.success) {
  console.error("❌ Invalid AI Response:", result.error.format());
} else {
  console.log("✅ AI Response is Valid!", result.data);
}

🔹 Why use Zod?

✅ Flexible for dynamic AI responses

✅ Works seamlessly with TypeScript

✅ Provides detailed error messages

Which One Should You Use?

  • Use AJV when integrating AI APIs that return structured, predictable JSON data.
  • Use Zod when working with dynamic, AI-generated responses that may have optional fields.

🚀 Best Practice: Always validate AI API responses before passing them to your frontend. This prevents unpredictable errors and ensures a smooth user experience!

🔥 Bonus Tip: If you’re using OpenAI or similar APIs, you can prompt the AI to return a schema-compliant response like this:

Return a JSON object strictly following this structure: 
{
  "name": "string",
  "age": "number",
  "email": "string (optional)"
}
Ensure it meets JSON schema validation.

…but still validate it in code! AI doesn’t always listen. 😅

Let me know if you want more AI API validation tips! 🚀


This content originally appeared on DEV Community and was authored by Elvis Ansima