Claude API Structured Output Validation Guide
What "structured output" means for Claude
The Claude API doesn't have a dedicated JSON mode like some other LLM APIs. Instead, you get structured output by combining three techniques: prompting Claude to produce JSON, using tool calling (also called function calling) to force a schema, and validating the result on your side before it touches your database or downstream code. If you're searching for a validation guide, you're probably hitting one of two problems: Claude occasionally returns malformed JSON, or it returns valid JSON that doesn't match the shape your application expects.
Both problems are solvable, and neither requires exotic infrastructure. This guide covers the three reliable ways to get structured output from Claude, how to validate it with JSON Schema or a library like Zod, and what to do when validation fails.
Method 1: Tool use for guaranteed schema shape
The most reliable way to get structured output from Claude is tool calling. You define a tool with an input schema, and Claude returns a tool_use block that matches that schema far more consistently than free-text JSON in a message body.
{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"tools": [
{
"name": "extract_invoice",
"description": "Extract structured invoice data",
"input_schema": {
"type": "object",
"properties": {
"vendor": { "type": "string" },
"total": { "type": "number" },
"currency": { "type": "string" },
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"amount": { "type": "number" }
},
"required": ["description", "amount"]
}
}
},
"required": ["vendor", "total", "currency"]
}
}
],
"tool_choice": { "type": "tool", "name": "extract_invoice" },
"messages": [
{ "role": "user", "content": "Invoice text here..." }
]
}
Setting tool_choice to force that specific tool removes the chance that Claude responds with plain text instead of the structured call. This is the approach to reach for whenever you need a fixed shape — extraction, classification, routing decisions, form filling. Full details are in the tool use docs.
Method 2: Prompted JSON with a strict system prompt
Tool use isn't always the right fit, especially when the output is more free-form (a generated article with metadata, a multi-section report). In those cases, you prompt for JSON directly and validate afterward.
You must respond with valid JSON only, matching this exact shape:
{
"title": string,
"summary": string,
"tags": string[],
"confidence": number between 0 and 1
}
Do not include any text before or after the JSON object.
This works most of the time, but "most of the time" isn't good enough for production. Claude can still wrap the JSON in a code block, add a trailing sentence, or occasionally produce a truncated object if max_tokens is too low. Treat prompted JSON as "likely structured" and validate it like untrusted input — because it is.
Method 3: Validate with JSON Schema or Zod
Whichever method produced the output, run it through a schema validator before using it. In Node, Zod is a common choice because it gives you both a parser and TypeScript types from one definition:
import { z } from "zod";
const InvoiceSchema = z.object({
vendor: z.string(),
total: z.number(),
currency: z.string().length(3),
line_items: z.array(
z.object({
description: z.string(),
amount: z.number(),
})
).optional(),
});
function parseInvoice(raw) {
const parsed = JSON.parse(raw);
return InvoiceSchema.parse(parsed); // throws on mismatch
}
If you're not in a JS/TS stack, standard JSON Schema with a validator like ajv, jsonschema (Python), or json-schema (Go) does the same job. The key practice is: never trust the LLM output shape implicitly, even when you used tool calling and gave it a schema. Models drift, prompts get edited, and edge cases (empty arrays, null vs. missing fields, numbers returned as strings) slip through.
Handling validation failures
When validation fails, you have three realistic options:
- Retry with the error attached. Send Claude the validation error message and ask it to fix the output. This works well and rarely needs more than one retry.
- Lower the temperature and re-ask. If you're not already at
temperature: 0or close to it for structured tasks, start there — it meaningfully reduces malformed output. - Fall back to a default or flag for manual review. For high-stakes fields (payment amounts, legal clauses), don't auto-correct; surface the failure.
async function extractWithRetry(rawText, attempt = 1) {
const response = await callClaude(rawText);
try {
return InvoiceSchema.parse(JSON.parse(response));
} catch (err) {
if (attempt >= 2) throw new Error("Validation failed after retry");
return extractWithRetry(
`${rawText}\n\nPrevious attempt failed validation: ${err.message}. Return corrected JSON only.`,
attempt + 1
);
}
}
Common pitfalls
- Missing
requiredfields in your schema. If a field is optional in your JSON Schema but your code assumes it's always present, you'll get runtime errors that look like "Claude's fault" but aren't. - Numbers as strings. Claude sometimes returns
"total": "149.99"instead of149.99, especially in prompted JSON. Coerce types during validation rather than failing outright, if that's acceptable for your use case. - Truncated output. If
max_tokensis too low, the JSON gets cut off mid-object. Checkstop_reasonin the response —max_tokensas the stop reason on a JSON task is a reliable signal to increase the limit. - Schema drift over time. If you change your schema, old cached outputs or prompt templates with the previous shape can keep producing mismatches. Version your schemas alongside your prompts.
Where this fits if you're exposing Claude as an API
If your product calls Claude on behalf of your users or team, structured output validation becomes a shared concern across every endpoint that touches the model. SubToAPI turns your Claude access into a standard HTTPS API with its own sub_live_ keys, so your validation layer sits on top of normal REST calls instead of SDK-specific plumbing — see the messages docs for request/response shapes and the tool use docs for schema-forced calls. Usage metadata is returned with every response, which is useful if you're logging validation failure rates per key or per team. Start with the quickstart or check pricing if you're deciding between Solo, Team, and Scale plans; a free trial is available at signup.
questions
Does the Claude API have a built-in JSON mode? No. Claude doesn't have a dedicated JSON-only response mode. You get structured output through tool calling with an input schema, or by prompting for JSON and validating the result yourself.
What's the most reliable way to force a specific output shape? Tool use with tool_choice set to a specific tool. It constrains Claude's output far more tightly than prompted JSON and is the right default for extraction and classification tasks.
How should I handle output that fails schema validation? Retry once with the validation error appended to the prompt at a low temperature. If it still fails, fall back to a default for low-stakes fields or flag the request for manual review for anything high-stakes.