intermediate12 min read· Module 6, Lesson 4
📋Structured Outputs
Get guaranteed JSON responses that match your schema
Structured Outputs
When building applications, you need Claude to respond in a specific format you can parse. Structured outputs guarantee Claude's response matches your JSON schema.
The Problem Without Structured Outputs
// Without structured outputs — might get invalid JSON!
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{
role: "user",
content: "Extract the name and email from: John Smith, john@example.com"
}]
});
// Could return: "Name: John Smith, Email: john@example.com"
// Or: { "name": "John Smith" ... }
// Or anything else! 😱The Solution: output_config
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{
role: "user",
content: "Extract the name and email from: John Smith, john@example.com"
}],
output_config: {
format: {
type: "json_schema",
schema: {
type: "object",
properties: {
name: { type: "string" },
email: { type: "string" }
},
required: ["name", "email"],
additionalProperties: false
}
}
}
});
// GUARANTEED to return:
// { "name": "John Smith", "email": "john@example.com" }With SDK Helper (Recommended)
Python with Pydantic:
from pydantic import BaseModel
from anthropic import Anthropic
class ContactInfo(BaseModel):
name: str
email: str
company: str | None
client = Anthropic()
response = client.messages.parse(
model="claude-sonnet-4-6",
max_tokens=1024,
output_format=ContactInfo,
messages=[{
"role": "user",
"content": "Extract info: Sarah at Acme Corp, sarah@acme.com"
}]
)
contact = response.parsed_output
print(contact.name) # "Sarah"TypeScript with Zod:
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
const ContactSchema = z.object({
name: z.string(),
email: z.string(),
company: z.string().nullable()
});
const response = await client.messages.parse({
model: "claude-sonnet-4-6",
max_tokens: 1024,
output_config: { format: zodOutputFormat(ContactSchema) },
messages: [{ role: "user", content: "..." }]
});Common Use Cases
| Use Case | Schema Example |
|---|---|
| Data extraction | name, email, phone from text |
| Classification | category, confidence, tags |
| API responses | status, data, errors |
| Form parsing | structured fields from documents |
| Sentiment analysis | sentiment, score, keywords |
Important Rules
additionalPropertiesmust befalse- No recursive schemas
- Max 20 strict tools per request
- First request has extra latency (grammar compilation)
Next up: Prompt engineering — the art of writing effective prompts.