DEV Community

Cover image for How to Validate AI API Responses with Zod and AJV (and Avoid Breaking Your Frontend)
Elvis Ansima
Elvis Ansima

Posted on

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

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
Enter fullscreen mode Exit fullscreen mode

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!");
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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.
Enter fullscreen mode Exit fullscreen mode

…but still validate it in code! AI doesn’t always listen. πŸ˜…

Let me know if you want more AI API validation tips! πŸš€

Top comments (0)