HomeAdvanced FeaturesStructured Outputs
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

JavaScript
// 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

JavaScript
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:

Python
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:

TypeScript
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 CaseSchema Example
Data extractionname, email, phone from text
Classificationcategory, confidence, tags
API responsesstatus, data, errors
Form parsingstructured fields from documents
Sentiment analysissentiment, score, keywords

Important Rules

  • additionalProperties must be false
  • 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.