~/academy $ claude learn structured-outputs
Structured outputs: reliable JSON from Claude
How to get schema-valid JSON from the Claude API with structured outputs and strict tool use, the schema rules, and what you still need to validate. 8 min
$ Read
Two features, one guarantee
Structured outputs constrain Claude's output to your JSON schema while it is being generated, so the response is valid JSON with the fields and types you asked for. You no longer need retry loops for broken JSON.
There are two parts. JSON outputs (output_config.format) shape Claude's reply itself. Strict tool use (strict: true on a tool definition) guarantees a tool's input matches its schema. You can use either or both in one request. Both are available on all current models.
This replaces older tricks. Prefilling the start of the answer returns a 400 error on current models, and the old output_format parameter on messages.create is deprecated in favour of output_config.
Lesson notes: Structured outputs: reliable JSON from Claude
Everything in this lesson as text, for revision or to read without the interactive steps. By the end you will be able to: You extract data into a Pydantic model that always parses, and you handle the few cases where it can still fail.
Step 1 of 6 · Read
Two features, one guarantee
Structured outputs constrain Claude's output to your JSON schema while it is being generated, so the response is valid JSON with the fields and types you asked for. You no longer need retry loops for broken JSON.
There are two parts. JSON outputs (
output_config.format) shape Claude's reply itself. Strict tool use (strict: trueon a tool definition) guarantees a tool'sinputmatches its schema. You can use either or both in one request. Both are available on all current models.This replaces older tricks. Prefilling the start of the answer returns a 400 error on current models, and the old
output_formatparameter onmessages.createis deprecated in favour ofoutput_config.Step 2 of 6 · Read
The easy way: Pydantic and messages.parse
The docs recommend
client.messages.parsewith a Pydantic model. The SDK turns your class into a schema, sends it asoutput_config.format, validates the reply and gives you a typed object inparsed_output.If you are not using Pydantic, pass a raw schema to
messages.createinoutput_configandjson.loadsthe text block yourself.Pydantic (recommended) from pydantic import BaseModel import anthropic class Lead(BaseModel): name: str email: str plan_interest: str demo_requested: bool client = anthropic.Anthropic() response = client.messages.parse( model="claude-opus-5-5", max_tokens=1024, messages=[{"role": "user", "content": "Extract the lead: Priya Shah (priya@example.com) wants a demo of the Team plan next Tuesday."}], output_format=Lead, ) lead = response.parsed_output print(lead.email)Raw JSON schema response = client.messages.create( model="claude-opus-5-5", max_tokens=1024, messages=[{"role": "user", "content": "Extract the lead: ..."}], output_config={ "format": { "type": "json_schema", "schema": { "type": "object", "properties": { "name": {"type": "string"}, "email": {"type": "string"}, "demo_requested": {"type": "boolean"}, }, "required": ["name", "email", "demo_requested"], "additionalProperties": False, }, } }, )Step 3 of 6 · Read
Schema rules (checked 18 November 2026)
Every object must set
additionalPropertiesto false, so Claude can only return keys you listed. Supported: objects, arrays, strings, numbers, integers, booleans, null,enum,const,anyOf,$refand common string formats such asdateandemail.Not supported: recursive schemas,
oneOf(useanyOf), number limits such asminimumandmaximum, and string length limits such asminLength. A raw schema that uses them returns a 400 error. The SDK helpers move those constraints into the field description and check them after the reply arrives.The first request with a new schema is slower while it compiles; the compiled version is cached for 24 hours. A request can have at most 20 strict tools, 24 optional parameters and 16 union-type parameters across all its schemas. Structured outputs cannot be combined with citations.
Step 4 of 6 · Read
What you still have to check
Check `stop_reason` first. If it is
refusal, the output may not match your schema. If it ismax_tokens, the JSON may be cut off: retry with a higher limit.Enum capitalisation is not guaranteed. Claude might return
Conversation Topic 3for an enum value writtenConversation topic 3. Compare enum values without regard to case, and never rely on values that differ only in capitals.Business rules are yours. A schema guarantees shape, not truth. Check that dates are in range, totals add up and IDs exist in your database. Also avoid fields that ask for step-by-step reasoning, which can trigger a refusal; ask for a short explanation instead.
Guard before you trust it if response.stop_reason == "max_tokens": raise RuntimeError("Output cut off: retry with a higher max_tokens") if response.stop_reason == "refusal": raise RuntimeError("Claude declined this request") lead = response.parsed_output if "@" not in lead.email: raise ValueError("Email failed our own check")Step 5 of 6 · Quiz
Check your understanding
Your raw schema has `"minimum": 0` on a price field and the request returns a 400 error. What do you do?
- Retry until it works.
- Switch to prefill and ask for JSON in the prompt.
- Remove `minimum` from the schema (or use the SDK helper, which moves it into the description) and check the price is not negative in your code.
Show the answer
Remove `minimum` from the schema (or use the SDK helper, which moves it into the description) and check the price is not negative in your code. Numeric limits are not supported in the schema itself. Keep the rule, but enforce it after parsing.
Step 6 of 6 · Sort
Guaranteed or still your job?
With structured outputs on, which of these does the API guarantee?
- The reply parses as valid JSON (when it finished normally)
- Every required field is present
- Field types match, for example a boolean is a boolean
- Invoice line items add up to the stated total
- A complete object when stop_reason is max_tokens
- The exact capitalisation of enum values
Show the answers
- The reply parses as valid JSON (when it finished normally): Guaranteed by the API. Constrained decoding produces schema-compliant JSON.
- Every required field is present: Guaranteed by the API. Required fields are part of the schema the output must follow.
- Field types match, for example a boolean is a boolean: Guaranteed by the API. Types are enforced during generation.
- Invoice line items add up to the stated total: Still your job. That is a business rule. Check it in your code.
- A complete object when stop_reason is max_tokens: Still your job. A cut-off response may be incomplete. Check stop_reason and retry.
- The exact capitalisation of enum values: Still your job. The docs say enum casing is not guaranteed, so compare without regard to case.