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! π
Top comments (0)