Structured Outputs

Structured outputs are the SDK workflow for asking Claude to return data that another program can consume without fragile string scraping. In the Messages API, the generated TypeScript surface exposes output-format and output-configuration types alongside the normal message, content-block, streaming-event, and tool-use types. That matters because a production integration usually needs two guarantees at once: the model should aim at a predictable JSON shape, and the client should parse or validate the result before it enters a database, queue, UI, or downstream agent step. Sources: src/resources/messages/index.ts, src/resources/beta/messages/index.ts

The first-party Claude documentation describes two complementary structured-output mechanisms: JSON outputs through an output configuration format, and strict tool use through schema validation for tool names and tool inputs. In SDK terms, JSON outputs are a Messages request concern, while strict tool use is a tool-definition concern that can be combined with the same request. The generated stable Messages index exports names such as OutputConfig, JSONOutputFormat, InputJSONDelta, RawMessageStreamEvent, ContentBlock, and Message, which are the public type anchors a TypeScript caller sees when building this workflow. Sources: src/resources/messages/index.ts

Purpose and Scope

Use this page when you want a typed, repeatable path from a prompt to validated JSON. The page focuses on the stable Messages surface and the beta Messages surface because those are the requested source-backed entry points for structured output behavior. It also covers streaming parsing because structured data can arrive as incremental server-sent events, and those events may contain JSON deltas rather than a complete final document. The goal is not to replace runtime validation, but to show where the SDK gives you typed request and response shapes and where your application should add schema checks. Sources: src/resources/messages/index.ts, src/resources/beta/messages/messages.ts

The practical distinction is important. A TypeScript type describes what the SDK expects at compile time, but real model output is still data arriving over the network. For non-streaming calls, your application can inspect the final message content and then validate it against JSON Schema, Zod, or another validator. For streaming calls, your application should accumulate partial content or input deltas before parsing, because fine-grained tool streaming and incremental JSON deltas can expose incomplete fragments. The official fine-grained streaming guidance warns that partial or invalid JSON is possible when validation is intentionally skipped for latency. Sources: src/resources/messages/index.ts

Relevant Source Files

  • src/resources/messages/index.ts - Stable generated Messages exports, including Message, ContentBlock, OutputConfig, JSONOutputFormat, InputJSONDelta, RawMessageStreamEvent, and related stream event types used by structured-output callers.
  • src/resources/beta/messages/index.ts - Beta generated Messages barrel that re-exports beta message, content, thinking, citation, tool, and output-related types for beta callers.
  • src/resources/beta/messages.ts - Beta namespace bridge that re-exports the beta messages index, making beta Messages resources available through the generated beta package structure.
  • src/resources/beta/messages/messages.ts - Generated beta Messages resource implementation and type definitions for beta message creation, streaming, and related message behavior.
  • src/resources/beta/messages/batches.ts - Beta Message Batches resource showing how beta message requests are submitted in batches with beta headers and request options.
  • src/internal/detect-platform.ts - Runtime detection and platform header support used by requests across Node, Deno, edge, browser, and unknown environments.

Core Primitives

The core primitives are request configuration, response content, stream events, and validators. Request configuration is where you tell Claude the JSON shape you want, either through an output configuration format or through tool definitions with strict schema requirements. Response content is the final data you inspect after a normal Messages call. Stream events are the incremental records you receive when streaming is enabled, including raw message events, content-block events, and deltas. Validators are your application’s final gate: JSON Schema, Zod, or another runtime checker should decide whether the parsed object is safe to use. Sources: src/resources/messages/index.ts

The stable Messages index is the primary source of public names for these primitives. Its exports include JSONOutputFormat and OutputConfig for output formatting, Message and MessageParam for the surrounding request and response model, ContentBlock and ContentBlockParam for message content, and InputJSONDelta plus raw stream event types for incremental processing. The beta index mirrors this generated style with beta-prefixed types and resources, which lets beta callers use the same mental model while opting into beta features. Sources: src/resources/messages/index.ts, src/resources/beta/messages/index.ts

System-to-Code Mapping

Reader taskSDK surface to look forSource grounding
Ask Claude for JSONOutputConfig and JSONOutputFormat on Messages request typessrc/resources/messages/index.ts
Validate final outputMessage and ContentBlock response types, then application JSON Schema or Zod validationsrc/resources/messages/index.ts
Stream structured dataRawMessageStreamEvent and InputJSONDelta-style event handlingsrc/resources/messages/index.ts
Use beta structured-output featuresBeta Messages exports and beta resource bridgesrc/resources/beta/messages/index.ts, src/resources/beta/messages.ts, src/resources/beta/messages/messages.ts
Run many structured requests asynchronouslyBeta message batch creation with per-request paramssrc/resources/beta/messages/batches.ts
Understand runtime contextPlatform detection and Stainless runtime headerssrc/internal/detect-platform.ts

This mapping keeps the responsibilities separated. The SDK’s generated resources define the transport shape, request options, path construction, headers, and TypeScript exports. The Claude API enforces supported structured-output behavior for the request you send. Your application still owns the business schema, error handling, retries, and storage decisions. For example, a classifier might ask for a JSON object with label and confidence fields, but the application should still reject missing fields, unexpected enum values, or a confidence value outside its accepted range before acting on the result. Sources: src/resources/messages/index.ts, src/resources/beta/messages/batches.ts

Execution Flow

A typical non-streaming flow starts by creating a Messages request with the model, messages, token limit, and an output configuration that describes the JSON format you expect. The response should then be treated as untrusted structured data until it is parsed and validated. If you use JSON Schema directly, keep the schema close to the code that consumes the object so changes are reviewed together. If you use Zod, define the Zod schema first, infer the TypeScript type from it, and validate the parsed result before using it. Sources: src/resources/messages/index.ts

For streaming, design the parser as a small state machine rather than assuming each event contains a complete JSON document. The stable exports include raw stream event and delta-oriented names, which signals that callers should expect incremental updates. Accumulate text or JSON input fragments, track content-block boundaries, and only parse when the stream has delivered a complete candidate value. If a stream ends early because of a token limit or transport interruption, return a recoverable error to the caller instead of passing a partial object downstream. Sources: src/resources/messages/index.ts

Batch execution follows the same validation rule, but the timing changes. The beta Batches resource sends multiple Message creation requests and notes that batches begin processing immediately and can take up to twenty-four hours to complete. The implementation posts to the beta message-batches endpoint, adds the message-batches beta header, and accepts request options plus optional beta lists and user profile headers. That means each individual structured-output request in a batch should carry its own prompt and schema expectations, and each result should be validated independently when retrieved. Sources: src/resources/beta/messages/batches.ts

API Components and Configuration Details

The beta namespace is organized as a generated bridge: the beta messages module re-exports the messages index, and that index re-exports Batches and Messages plus a large set of beta-prefixed data types. This is useful when you are comparing stable and beta structured-output behavior because the import paths and resource naming remain parallel. Prefer the stable Messages resource unless a beta feature explicitly requires the beta namespace, then isolate the beta call behind a small adapter so the rest of the application receives the same validated domain object. Sources: src/resources/beta/messages.ts, src/resources/beta/messages/index.ts, src/resources/beta/messages/messages.ts

Runtime behavior is also part of reliable structured output. The internal platform detector identifies Deno, edge, Node, browser, and unknown environments, then produces Stainless headers such as language, package version, operating system, architecture, runtime, and runtime version. These headers do not change your JSON schema, but they help the SDK send consistent request metadata across supported JavaScript runtimes. When troubleshooting environment-specific parsing or streaming issues, confirm whether the application is running in Node, Deno, an edge runtime, or an explicitly enabled browser context. Sources: src/internal/detect-platform.ts

Implementation Guidance

Keep prompts, schemas, and validators aligned. A useful pattern is to name the expected object in the prompt, describe each field in ordinary language, provide the JSON Schema or tool input schema, and then validate the returned object with the same constraints your downstream code expects. Avoid silently coercing malformed output into a valid-looking object; that can hide model, prompt, or schema drift. Instead, log enough request context to debug safely, return a validation error, and decide whether the caller should retry, ask Claude to repair the object, or fall back to a manual review path. Sources: src/resources/messages/index.ts

Next, read the Messages API and Streaming Responses pages for the core request and event lifecycle, then read the Tool Use Overview and JSON Schema and Zod Helpers pages if your structured output should be represented as strict tool calls. If you plan to process many schema-constrained prompts offline, continue to Message Batches so you can understand polling, result retrieval, and per-result validation. For beta features, compare the stable and beta Messages references before adopting beta-only request fields in shared application code. Sources: src/resources/messages/index.ts, src/resources/beta/messages/index.ts, src/resources/beta/messages/batches.ts