Structured outputs let you ask an LLM API for data in a shape you define — usually JSON that must match a JSON Schema — so your code can parse the response without regex cleanup or retry loops. The meaningful difference from simply prompting a model to “reply in JSON” is enforcement: providers such as OpenAI and Anthropic constrain generation so the response conforms to the schema you supply, rather than hoping the model complies. OpenAI describes the feature as ensuring the model will always generate responses that adhere to your supplied JSON Schema, so you do not have to worry about omitted required keys or hallucinated enum values (OpenAI structured outputs).
This guide is for developers and automation builders who already make API calls and want machine-readable results they can trust downstream. It explains how JSON mode differs from schema-constrained output, shows how to send a schema to OpenAI and Claude, and covers the failure modes that remain even after the JSON is guaranteed to be valid.
JSON mode and structured outputs are not the same thing
The two terms are often used interchangeably, which causes avoidable confusion.
JSON mode is the weaker contract. You tell the API that the response should be JSON, and the model returns syntactically valid JSON — but nothing guarantees which keys exist, what types they hold, or whether an enum value is one you actually defined. Your application still has to validate.
Structured outputs add a schema to the request and enforce it during generation. Anthropic frames this as constrained decoding: the model’s token choices are restricted so the output stays on a valid path through your schema. The same documentation lists the typical symptoms of not using it — parsing errors from invalid JSON syntax, missing required fields, inconsistent data types, and schema violations requiring error handling and retries — and states that structured outputs guarantee schema-compliant responses through constrained decoding (Anthropic structured outputs).
A useful way to hold the distinction: JSON mode constrains the syntax. Structured outputs constrain the contract. Neither constrains the meaning — a schema-valid response can still contain a wrong date or a misattributed name. Validation of shape and validation of truth are separate problems, and only the first one is solved by the API.
What the major APIs actually expose
OpenAI supports JSON Schema in the REST API, and its Python and JavaScript libraries let you define the schema in code using pydantic.BaseModel and z.object respectively. The Ruby SDK supports schemas defined with Sorbet T::Struct and returns typed parsed results. The documented benefits are reliable type-safety without manual validation or retries, programmatically detectable safety refusals, and simpler prompting because you no longer need strongly worded formatting instructions.
Anthropic exposes two complementary features. JSON outputs are requested through output_config.format with type: "json_schema", and strict tool use is requested with strict: true, which guarantees schema validation on tool names and inputs. The two can be used independently or together in the same request, and the schema follows JSON Schema with some documented limitations. SDK helpers set the format field for you and parse the response into your language’s type.
Sending a schema with the OpenAI SDK
The JavaScript example below is taken from the OpenAI documentation. It defines a calendar event schema with Zod, attaches it to the request as a text format, and reads the parsed object back off the response.
import OpenAI from "openai";
import { zodTextFormat } from "openai/helpers/zod";
import { z } from "zod";
const openai = new OpenAI();
const CalendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const response = await openai.responses.parse({
model: "gpt-6-astra",
input: [
{ role: "system", content: "Extract the event information." },
{
role: "user",
content: "Alice and Bob are going to a science fair on Friday.",
},
],
text: {
format: zodTextFormat(CalendarEvent, "event"),
},
});
const event = response.output_parsed;Two details are worth noticing. First, the schema is passed as a named format ("event"), not as a prose instruction. Second, the result arrives as response.output_parsed — an object already shaped like the schema — rather than as a string you have to parse yourself. The equivalent Python flow uses a pydantic.BaseModel class in place of the Zod object.
Sending a schema to Claude
Anthropic’s request carries the schema in output_config.format. The shell example below follows the documented request shape, with the schema body abbreviated.
curl https://api.anthropic.com/v1/messages
-H "content-type: application/json"
-H "x-api-key: $ANTHROPIC_API_KEY"
-H "anthropic-version: 2023-06-01"
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Extract the key information from this email: ..."
}
],
"output_config": {
"format": {
"type": "json_schema",
"schema": { "...": "your JSON Schema goes here" }
}
}
}'Claude returns valid JSON matching the schema inside the response’s text content block, and the SDK helpers parse it into your type. If you are also using tools, strict: true applies the same guarantee to tool names and inputs.
Verifying that the contract held
Even with enforcement in place, a short verification step is worth keeping in the pipeline, because it catches the difference between a schema that is valid and a schema that is complete.
- Parse, do not pattern-match. Feed the response through a real JSON parser and your schema validator. If the provider returns a parsed object, re-validate it against the same schema your application will use later.
- Check that required fields are actually required. A schema where everything is optional will happily accept an empty object. If a field matters, mark it required.
- Check enum coverage. Inputs that map to no allowed enum value are a common source of semantic, not syntactic, failure.
- Log the raw response. Store the unparsed text alongside the parsed object so a later disagreement between expected and actual data can be investigated without re-running the call.
- Handle refusals explicitly. OpenAI notes that safety-based refusals are programmatically detectable, which means your code can branch on a refusal instead of treating it as malformed output.
Errors and edge cases that survive structured output
Schema enforcement removes a class of bugs; it does not remove all of them. The remaining ones cluster in a few places.
- Schema limitations. Anthropic documents that its schemas follow JSON Schema with some limitations. Deeply nested objects, recursive definitions, and unusual numeric constraints are the usual places where a schema that validates locally is rejected or simplified by the API. Test the schema against the provider before building logic on top of it.
- Semantic drift. The model can satisfy every type constraint and still assign the wrong value. Constrained decoding says nothing about factual accuracy.
- Refusals and empty results. A refusal is not a schema violation, and code that only handles parse failures will mishandle it.
- Prompt and schema mismatch. If the input text does not contain the field you asked for, the model must still emit something. Decide in advance whether that should be a null, an empty array, or an explicit “unknown” enum member.
- Over-constraining. Very large schemas increase prompt overhead and can reduce extraction quality. Splitting one sprawling schema into two focused calls is often cheaper than fighting a single giant one.
Structured outputs on local models
The same idea exists outside hosted APIs, and it is one of the more practical reasons to run a model locally. Grammar-constrained or guided decoding — implemented in tools such as llama.cpp’s GBNF grammars, Outlines, and vLLM’s guided decoding — restricts sampling to tokens that keep the output inside a defined grammar or schema. The mechanics differ from hosted structured outputs, but the contract to your downstream code can be identical: a JSON object that validates against the same schema.
Two caveats apply when you self-host. First, constrained decoding adds per-token overhead, so measure throughput on your own hardware rather than assuming parity with unconstrained generation. Second, grammar support is implementation-specific: a JSON Schema feature that works in one runtime may be unsupported in another, so validate your schema against the runtime you actually deploy. As with hosted APIs, the guarantee is about shape, not truth.
Where this fits in automation and publishing workflows
Structured outputs are most valuable at the boundary between a model and deterministic code. In a WordPress automation pipeline, for example, a model might classify an incoming message, extract a title and summary, and propose tags. If that step returns a schema-validated object, the automation layer can act on typed fields instead of parsing prose, and failures become visible as validation errors rather than as malformed posts.
The design decision that matters most is where the schema stops and human review begins. A schema can guarantee that a title field is a non-empty string; it cannot guarantee the title is accurate or appropriate. For anything that publishes, notifies, or triggers a downstream system, keep a review checkpoint or a dry-run mode, and treat the schema as a guardrail on structure rather than on editorial judgment.
What to do next
Start with the smallest schema that solves your problem: one object, a handful of required fields, and enums for any field that should only take a known set of values. Send it to one provider, log both the raw and parsed responses, and confirm that your validator accepts what the API returns. Then add the two checks that catch most real-world failures — an explicit refusal branch and a semantic sanity check on the extracted values — before wiring the call into anything that writes data.
If you are building this into a workflow and hit a schema the API rejects, share the schema shape, the provider, and the exact error message in the community so others can compare notes.
FAQ
Does structured output guarantee the extracted values are correct?
No. Structured outputs guarantee that the response conforms to your JSON Schema, which covers required keys, types, and enum values. They do not guarantee that the values are factually accurate, so semantic checks remain your responsibility.
Can JSON outputs and strict tool use be combined in one Claude request?
Yes. Anthropic documents the two features as complementary and states they can be used independently or together in the same request.
What happens if the model refuses a request?
OpenAI documents safety-based refusals as programmatically detectable, so your code can branch on a refusal rather than treating it as malformed output. A refusal is not the same event as a schema violation.
Can local models produce schema-constrained output?
Yes, through grammar-constrained or guided decoding in runtimes such as llama.cpp, Outlines, and vLLM. Support for specific JSON Schema features varies by implementation, and constrained decoding adds per-token overhead, so verify both against the runtime you deploy.