← Blog

Claude API Structured Output with Pydantic Models

2026-11-17 · 5 min read · SubToAPI Team

Getting structured output from Claude with Pydantic

If you're searching for "claude api structured output pydantic models," you're probably trying to get Claude to return data that matches a Python class instead of free-form text you have to parse with regex and hope for the best. The short answer: Claude doesn't have a native response_format like some other APIs, but you can get fully validated, type-safe output by combining tool use (function calling) with Pydantic's JSON schema generation. Claude calls a "tool" whose input schema is derived from your Pydantic model, and you validate the returned arguments directly against that model.

This pattern is reliable, works with nested objects, enums, optional fields, and lists, and avoids the fragile "please respond only in JSON" prompting approach that breaks the moment Claude adds a stray sentence before the JSON blob.

Why tool use beats prompting for JSON

Asking Claude to "output valid JSON matching this schema" in the system prompt works most of the time, but "most of the time" isn't good enough for production pipelines. Problems you'll hit:

Tool use solves this differently: you give Claude a tool definition with a strict JSON schema, and the model is specifically trained to produce arguments that match that schema when it decides to call the tool. You can even force the tool call with tool_choice, guaranteeing structured output on every request.

Step 1: Define your Pydantic model

from pydantic import BaseModel, Field
from typing import Optional, Literal

class LineItem(BaseModel):
    name: str
    quantity: int
    unit_price: float

class Invoice(BaseModel):
    invoice_number: str
    customer_name: str
    status: Literal["paid", "pending", "overdue"]
    items: list[LineItem]
    notes: Optional[str] = Field(default=None)

Step 2: Convert the model to a tool schema

Pydantic can generate a JSON schema directly from the model, which you reshape into the tool format Claude expects:

import anthropic

tool_schema = Invoice.model_json_schema()

tools = [
    {
        "name": "extract_invoice",
        "description": "Extract structured invoice data from the text",
        "input_schema": tool_schema,
    }
]

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "tool", "name": "extract_invoice"},
    messages=[
        {"role": "user", "content": "Invoice #4471 for Acme Corp, 2 widgets at $12.50 each, status: pending."}
    ],
)

Forcing tool_choice to a specific tool name means Claude will always respond with a structured tool call rather than a conversational message, which is exactly what you want for extraction and data pipeline tasks.

Step 3: Parse the response into your model

tool_use_block = next(
    block for block in response.content if block.type == "tool_use"
)

invoice = Invoice.model_validate(tool_use_block.input)
print(invoice.customer_name, invoice.status)

If Claude's output doesn't match the schema — wrong type, missing required field — Pydantic raises a ValidationError immediately, so you catch malformed data before it hits your database instead of discovering it three steps downstream.

Handling nested models and lists

Pydantic's model_json_schema() automatically resolves nested models (like LineItem inside Invoice) into $defs references, which Claude handles correctly. You generally don't need to flatten anything manually. If you're using Pydantic v1 instead of v2, use .schema() instead of .model_json_schema() — the structure is nearly identical.

One tip: keep descriptions on your fields. Claude uses the description field in the schema to understand what to extract, not just the type:

class Invoice(BaseModel):
    invoice_number: str = Field(description="The invoice ID, e.g. INV-4471")
    status: Literal["paid", "pending", "overdue"] = Field(
        description="Payment status based on context clues like due dates"
    )

Vague field names with no description lead to more extraction errors than almost any other factor.

Validating and retrying

Even with tool use, you should still wrap validation in a retry loop for production use — occasionally a model will return a string where an int was expected, especially with ambiguous input text:

from pydantic import ValidationError

def extract_invoice(text: str, retries: int = 2) -> Invoice:
    for attempt in range(retries + 1):
        response = client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=1024,
            tools=tools,
            tool_choice={"type": "tool", "name": "extract_invoice"},
            messages=[{"role": "user", "content": text}],
        )
        tool_block = next(b for b in response.content if b.type == "tool_use")
        try:
            return Invoice.model_validate(tool_block.input)
        except ValidationError:
            if attempt == retries:
                raise
    raise RuntimeError("unreachable")

Using this through SubToAPI

If your team is already accessing Claude through SubToAPI — turning a Claude subscription into a standard HTTPS API with sub_live_... keys — this same pattern works unchanged. The tool-use request format is compatible, so you point your existing client at https://api.subtoapi.app/v1/messages, pass your SUBTOAPI_KEY, and keep your Pydantic validation layer exactly as is:

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", "input_schema": {...}}],
    "tool_choice": {"type": "tool", "name": "extract_invoice"},
    "messages": [{"role": "user", "content": "Invoice #4471..."}]
  }'

This is useful when multiple team members or services need API access to the same underlying Claude subscription with separate keys, usage tracking per key, and no shared credentials floating around in config files. See the tool use docs and quickstart for the full request/response shapes, or check pricing if you're evaluating team seats.

Common mistakes to avoid

questions

Does Claude have a native structured output / JSON mode like OpenAI's response_format? Not exactly. Claude's equivalent is tool use with a forced tool_choice, which achieves the same guarantee — the model must return arguments matching your schema.

Can I use Pydantic v1 and v2 interchangeably for this? Mostly yes. The schema generation method differs (.schema() vs .model_json_schema()), but the resulting JSON schema structure Claude receives is nearly identical in both.

What happens if Claude returns data that doesn't match my Pydantic model? model_validate() raises a ValidationError with details on which field failed, so you can catch it, log it, and retry the request rather than silently passing bad data downstream.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →