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! πŸš€

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay