Structured Outputs and JSON
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Free-form text is hard to put in a database. Asking Claude "reply in JSON" works most of the time, and "most of the time" is a bug waiting to happen. Structured outputs let you give the API a JSON schema and have the response constrained to match it. This lesson shows the request shape, a Pydantic helper in Python, a Laravel version with validation, and the limits you must design around.
Learning objectives
- Request schema-constrained JSON with
output_config.format.
- Use the Python SDK's
parse() with a Pydantic model.
- Know which schema features are supported and which cause a 400.
- Validate the meaning of the data even when the shape is guaranteed.
Prerequisites
The request
You send a JSON Schema in output_config.format. Claude returns valid JSON matching it in the response's text block:
{
"model": "claude-sonnet-5-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Extract: John Smith (john@example.com) wants the Enterprise plan and a demo."}],
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"plan_interest": {"type": "string"},
"demo_requested": {"type": "boolean"}
},
"required": ["name", "email", "plan_interest", "demo_requested"],
"additionalProperties": false
}
}
}
}
Every object in the schema must set additionalProperties to false. Structured outputs are available on the current models and on several earlier ones; the documentation lists them. A related feature, strict tool use (strict: true on a tool), applies the same idea to tool inputs and can be combined with JSON outputs (module 4).
Python with Pydantic
The recommended route is client.messages.parse(). You pass a Pydantic model as output_format; the SDK builds the schema, sends it, validates the response and gives you a typed object in parsed_output:
from pydantic import BaseModel
import anthropic
class ContactInfo(BaseModel):
name: str
email: str
plan_interest: str
demo_requested: bool
client = anthropic.Anthropic()
response = client.messages.parse(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Extract the contact details: John Smith (john@example.com) wants the Enterprise plan and a demo next Tuesday.",
}],
output_format=ContactInfo,
)
contact: ContactInfo = response.parsed_output
print(contact)
print(contact.email)
One trap from the documentation: a plain dict field is sent as an object with empty properties, so Claude can only return {}. Use a nested Pydantic model whenever the keys are known.
If you prefer a raw schema, use messages.create() with output_config and parse the text yourself. Note the check for a cut-off response first:
import json
import anthropic
SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"plan_interest": {"type": "string"},
"demo_requested": {"type": "boolean"},
},
"required": ["name", "email", "plan_interest", "demo_requested"],
"additionalProperties": False, # required on every object in a schema
}
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Extract: John Smith (john@example.com) wants Enterprise and a demo."}],
output_config={"format": {"type": "json_schema", "schema": SCHEMA}},
)
if message.stop_reason == "max_tokens":
raise RuntimeError("Output was cut off; the JSON is incomplete.") # raise max_tokens, never parse this
text = next(b.text for b in message.content if b.type == "text")
data = json.loads(text)
print(data["email"])
Laravel
In Laravel the same request goes through the HTTP client. The class below sends the schema, rejects any response that did not end normally, then runs Laravel's validator on the result. The schema guarantees the shape; the validator guards the meaning, for example that email is really an email address:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use RuntimeException;
class ContactExtractor
{
private const SCHEMA = [
'type' => 'object',
'properties' => [
'name' => ['type' => 'string'],
'email' => ['type' => 'string'],
'plan_interest' => ['type' => 'string'],
'demo_requested' => ['type' => 'boolean'],
],
'required' => ['name', 'email', 'plan_interest', 'demo_requested'],
'additionalProperties' => false, // every object in a schema must set this to false
];
/** @return array{name: string, email: string, plan_interest: string, demo_requested: bool} */
public function extract(string $text): array
{
$response = Http::withHeaders([
'x-api-key' => config('services.anthropic.key'),
'anthropic-version' => config('services.anthropic.version'),
])
->acceptJson()
->timeout(60)
->retry(3, 1000, fn ($e) => $e instanceof \Illuminate\Http\Client\ConnectionException
|| ($e instanceof \Illuminate\Http\Client\RequestException && in_array($e->response->status(), [429, 500, 529], true)),
throw: false)
->post('https://api.anthropic.com/v1/messages', [
'model' => config('services.anthropic.model'),
'max_tokens' => 1024,
'messages' => [['role' => 'user', 'content' => "Extract the contact details from this message:\n\n".$text]],
'output_config' => ['format' => ['type' => 'json_schema', 'schema' => self::SCHEMA]],
]);
if ($response->failed()) {
throw new RuntimeException('Claude request failed with status '.$response->status());
}
// A reply cut off by max_tokens, or a refusal, cannot be assumed to match your schema.
if ($response->json('stop_reason') !== 'end_turn') {
throw new RuntimeException('Unusable response, stop_reason='.$response->json('stop_reason'));
}
$json = collect($response->json('content', []))->firstWhere('type', 'text')['text'] ?? '';
$data = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
// The schema guarantees the shape; your own rules still guard what the data means.
return Validator::make($data, [
'name' => ['required', 'string', 'max:200'],
'email' => ['required', 'email'],
'plan_interest' => ['required', 'string', 'max:100'],
'demo_requested' => ['required', 'boolean'],
])->validate();
}
}
This class was exercised with Laravel's Http::fake() for three cases: a good reply, a reply cut off by max_tokens, and a well-formed reply with a bad email address. All three behaved as designed.
Schema limits
| Supported | Not supported |
| Types: object, array, string, integer, number, boolean, null | Recursive schemas |
enum (strings, numbers, booleans, nulls), const | Numerical constraints: minimum, maximum, multipleOf |
anyOf, allOf (not with $ref) | String constraints: minLength, maxLength |
$ref, $def, definitions (not external) | Array constraints beyond minItems of 0 or 1 |
String formats such as date-time, date, email, uri, uuid | additionalProperties other than false; some regex features |
An unsupported feature returns a 400 error. The SDK helpers can move unsupported constraints into field descriptions and still check them locally, which is another reason to keep your own validation.
Practical considerations
- First-request latency. The first time you use a schema, the API compiles a grammar, which adds latency. Compiled grammars are cached for 24 hours from last use. Changing the schema's structure invalidates the cache; changing only a
name or description does not.
- Extra input tokens. Claude receives an additional system prompt describing the format, so each request costs slightly more input.
- Prompt cache. Changing
output_config.format invalidates the prompt cache for that conversation thread.
- Truncation. If
stop_reason is max_tokens, the JSON is incomplete. Never parse it; raise max_tokens and retry. A refusal (a normal HTTP 200 with stop_reason: "refusal") should be treated as unusable too, because you cannot assume it matches your schema.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A CRM receives free-text enquiries from a web form. A Laravel job sends each one with the contact schema, stores the validated fields in MySQL columns, and routes "demo_requested = true" leads to a sales queue. Previously a regular expression tried to find emails and broke on every unusual signature. With a schema, the job's only failure modes are explicit: an API error, a cut-off, or a validation failure, each with its own handling.
Common errors and solutions
| Problem | Cause | Fix |
| 400 about the schema | Unsupported keyword, or an object missing additionalProperties: false. | Remove the keyword; validate that constraint in your own code. |
JSONDecodeError / JsonException | stop_reason was max_tokens. | Check stop_reason before parsing; raise max_tokens. |
A field always comes back as {} | A Pydantic dict field. | Use a nested model. |
| First request slow, later ones fast | Grammar compilation. | Expected; keep the schema stable. |
| Valid JSON, wrong facts | The schema guarantees shape, not truth. | Validate values; for important data, add a human review step. |
Security considerations
- Structured output does not make content trustworthy. The model read untrusted text; treat every extracted field as untrusted input and validate before use.
- Use parameterised queries when storing results; never build SQL from extracted strings.
- Escape values when rendering them in HTML.
Performance and cost considerations
Keep schemas small and stable to benefit from the grammar cache. Ask only for fields you will use, since every field is output tokens you pay for. For high-volume extraction, a small, fast model is often enough and much cheaper (lesson 1.2).
Key takeaways
- Send a JSON Schema in
output_config.format with type: "json_schema".
- In Python prefer
messages.parse() with a Pydantic model.
- Check
stop_reason before parsing, and validate meaning as well as shape.
- Unsupported schema keywords return a 400; plan validation for them.
Lesson recap: schema in, shaped JSON out, then check stop_reason and validate the data.
Knowledge check
- Where does the schema go in the request?
- What must every object in the schema set?
- Why check
stop_reason before parsing the JSON?
- Can you enforce
maxLength in the schema? What do you do instead?
- The JSON matches your schema but the email is wrong. Whose job is it to catch that?
Answers and explanations
- In the top-level
output_config parameter, as format with type: "json_schema" and a schema.
additionalProperties: false.
- If generation stopped at
max_tokens the JSON is incomplete, and a refusal should not be assumed to match the schema.
- No; string length constraints are not supported and cause a 400. Validate length in your own code.
- Yours. The schema guarantees structure, not correctness, so validate values in your application.
Official references and further reading
Related tutorials