Claude API JSON Schema Validation Output Guide
If you're trying to get the Claude API to return JSON that matches a specific schema every time, the short answer is: use tool use (function calling), not a "JSON mode" flag — Claude doesn't have one. Instead, you define a JSON Schema as a tool's input schema, force Claude to call that tool, and the model generates arguments that already conform to the schema's structure, types, and required fields.
This gets you most of the way to validated output, but it's not a guarantee on its own. Claude is very good at following schemas, but LLMs can still occasionally produce a malformed or semantically wrong value (a string where a number is expected, a missing optional field filled with a placeholder). The reliable pattern is: schema-constrained generation via tools, plus a cheap runtime validation pass on your side before you trust the data. This article covers both halves.
Why "JSON mode" doesn't fully solve this
Some APIs offer a strict JSON-output mode that guarantees syntactically valid JSON. That solves parsing, but it does not guarantee the JSON matches your schema — types, required keys, enums, nested structures. Tool use solves the schema problem directly because you're not asking Claude to "write JSON," you're asking it to call a function whose signature you control.
Step 1: Define your schema as a tool
Structure your schema the same way you would for any function-calling setup — type, properties, required, and constraints like enum or minimum/maximum where relevant.
{
"name": "extract_invoice",
"description": "Extract structured invoice data from text",
"input_schema": {
"type": "object",
"properties": {
"invoice_number": { "type": "string" },
"total_amount": { "type": "number" },
"currency": { "type": "string", "enum": ["EUR", "USD", "GBP"] },
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"quantity": { "type": "integer" },
"unit_price": { "type": "number" }
},
"required": ["description", "quantity", "unit_price"]
}
}
},
"required": ["invoice_number", "total_amount", "currency", "line_items"]
}
}
The more specific you are with enum, required, and numeric types, the less room Claude has to drift.
Step 2: Force the tool call
Set tool_choice so Claude has to use this tool rather than answering in free text. This is the single most important step for consistent structured output.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"tools": [{
"name": "extract_invoice",
"description": "Extract structured invoice data from text",
"input_schema": { "...": "see schema above" }
}],
"tool_choice": { "type": "tool", "name": "extract_invoice" },
"messages": [
{ "role": "user", "content": "Invoice #4471, total 1250.00 EUR, 2x Consulting hours at 500.00, 1x Setup fee at 250.00" }
]
}'
The response comes back as a tool_use content block with an input object — that object is your validated-by-construction JSON. If you're building against SubToAPI, this endpoint and the tool schema format work exactly like the standard Claude Messages API — see /docs/tools and /docs/messages for the full request/response shape.
Step 3: Validate the output anyway
Even with a forced tool call, run the input object through a real JSON Schema validator before you use it in production logic. This catches edge cases (unexpected enum values, out-of-range numbers) and gives you a clean failure path instead of a silent bad write to your database.
import Ajv from "ajv";
const ajv = new Ajv();
const validate = ajv.compile(invoiceSchema);
const toolCall = response.content.find(c => c.type === "tool_use");
const valid = validate(toolCall.input);
if (!valid) {
console.error(validate.errors);
// retry, fall back, or flag for human review
}
This two-layer approach — schema-constrained generation + post-hoc validation — is the pattern worth standardizing on. Treat the model's JSON like any other untrusted input from an external system.
Handling validation failures
When validation fails, don't just throw an error. A few practical options, roughly in order of preference:
- Retry with the validation errors in context. Send the invalid output and the specific Ajv/Zod error messages back to Claude in a follow-up message and ask it to correct the fields that failed. This is usually enough to fix one bad field without re-running the whole extraction.
- Lower
temperaturefor extraction tasks. Structured extraction doesn't need creativity;temperature: 0reduces variance in edge cases like ambiguous dates or currency symbols. - Tighten the schema. If a field keeps coming back wrong, it's often a schema problem, not a model problem — add
enumconstraints,patternregexes for IDs, or split an overloaded field into two more specific ones. - Log failures separately from successes. Schema validation failures are rare but not zero; track the rate so you know if a prompt or schema change made things worse.
Multiple schemas and nested extraction
For workflows that need to extract multiple independent structures from the same input (e.g., both invoice data and customer metadata), define multiple tools and let Claude call several in one turn, or call them one at a time if you need strict ordering. Each tool's input_schema is validated independently, which keeps your validation code simple and testable per schema.
If you're already calling the Claude API through SubToAPI for other parts of your product — chat, summarization, agents — you don't need a separate setup for structured extraction. The same sub_live_... key, the same /v1/messages endpoint, and the same tool_use mechanics apply, with usage metadata tracked per request in your dashboard so you can see exactly how much extraction workloads are costing you. Get started at /signup or check /docs/quickstart for the full request format.
Best practices checklist
- Always set
tool_choiceto force the specific tool when you need guaranteed structured output. - Use
enum,required, and numeric bounds aggressively — ambiguity in the schema becomes ambiguity in the output. - Validate with a real JSON Schema library (Ajv for JS,
jsonschemafor Python) rather than trusting the tool call blindly. - Keep
temperaturelow or zero for extraction-style tasks. - Build a retry loop that feeds validation errors back to the model instead of failing immediately.
questions
Does Claude have a native JSON mode like some other APIs? No. Claude guarantees valid, schema-conformant structure through tool use (function calling) rather than a dedicated JSON-output flag. Define a JSON Schema as a tool and force its use with tool_choice.
Is tool-use output guaranteed to match my schema exactly? It's very close in practice, but not formally guaranteed. Always run a server-side JSON Schema validation pass (e.g., Ajv) on the returned input object before using it downstream.
What should I do when validation fails? Retry by sending the validation errors back to Claude for correction, lower temperature to reduce variance, and tighten the schema with enum/pattern constraints if a specific field repeatedly fails.