# Structured Output

**Package:** Anthropic PHP | **Version:** 1 | **URL:** https://mozex.dev/docs/anthropic-php/v1/usage/structured-output

---

Structured output makes Claude answer in JSON that matches a schema you give it. The API enforces the schema while Claude writes, so a finished reply is JSON in that shape. This client builds the schema from a PHP class and turns the reply back into one.

## From a class

Describe the answer as a class with a constructor:

```php
use Anthropic\Schema\Schema;

class Contact
{
    public function __construct(
        public string $name,
        public string $email,
        public string $plan_interest,
        public bool $demo_requested,
    ) {}
}

$response = $client->messages()->create([
    'model' => 'claude-sonnet-5-5',
    'max_tokens' => 1024,
    'messages' => [
        ['role' => 'user', 'content' => 'Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.'],
    ],
    'output_config' => ['format' => Schema::format(Contact::class)],
]);

$contact = $response->parse(Contact::class);

$contact->name;           // 'John Smith'
$contact->demo_requested; // true
```

`Schema::format()` gives the `output_config.format` the API takes. Here that's `type: json_schema` with the class's schema: each constructor parameter a property, all four required, `additionalProperties: false`. `parse()` reads the reply's last text block, checks it against the schema, and builds the class.

## What a class can hold

| Parameter type | Schema |
|----------------|--------|
| `string`, `int`, `float`, `bool` | `string`, `integer`, `number`, `boolean` |
| A backed enum | Its values as an `enum`. A reply that differs only in case still matches, since the docs say Claude can change the case |
| `DateTimeImmutable`, `DateTime`, a class extending one (Carbon), `DateTimeInterface` | A `date-time` string, parsed back into the parameter's class (`DateTimeImmutable` for the interface) |
| Another class | A nested object, built the same way |
| `array` | A list of what `#[ListOf(Item::class)]` names, or a `@param list<string>` (`list<string>\|null` and `non-empty-list<string>` too) in the constructor's docblock |

A nullable parameter, or one with a default, is optional: the reply can leave it out, and you get `null` or the default. Every other one is required. The API takes at most 24 optional parameters in a request, across every strict schema in it. A class that holds itself, an untyped or `mixed` parameter, a pure enum, an array with no item type, a variadic parameter and a class that can't be built (abstract, or with a private constructor) throw an `InvalidArgumentException` as the schema is built, before anything is sent.

```php
use Anthropic\Schema\Attributes\Constraints;
use Anthropic\Schema\Attributes\Description;
use Anthropic\Schema\Attributes\ListOf;

#[Description('A sales lead from an email')]
class Lead
{
    public function __construct(
        public string $name,
        #[Constraints(format: 'email')] public string $email,
        public Plan $plan,
        public Company $company,
        #[ListOf(Company::class)] public array $previous_employers,
        #[Description('Seats wanted'), Constraints(minimum: 1, maximum: 500)] public ?int $seats = null,
    ) {}
}
```

In a docblock, a list holds a scalar or a fully qualified class (`list<\App\Data\Company>`): a short name can't be resolved without the file's imports, so `#[ListOf]` is the safer way.

## Constraints Claude doesn't take

The API takes `format` (one of `date-time`, `time`, `date`, `duration`, `email`, `hostname`, `uri`, `ipv4`, `ipv6` and `uuid`), `pattern` and `minItems` of 0 or 1. It refuses the rest. `Schema::format()` does what the official SDKs do with a class's schema. It removes each refused keyword and adds it to the property's description, so `minimum: 1, maximum: 500` reaches Claude as `{minimum: 1, maximum: 500}` in the description, closes every object with `additionalProperties: false`, and makes a `oneOf` an `anyOf`. `parse()` then checks the reply against the schema as you wrote it, so every constraint holds.

A schema array of your own goes to the API as it is, as the docs say a raw schema does. `Schema::sanitize($schema)` transforms one the same way when you want it to.

## When the reply isn't what you asked for

`parse()` throws a `StructuredOutputException`, whose `reason` says why:

| `reason` | When |
|----------|------|
| `refusal` | Claude refused, so the reply needn't match the schema: `stop_details` says why |
| `max_tokens` | The JSON was cut off. Send the request again with more `max_tokens` |
| `no_json` | The last text block isn't JSON, or the reply has no text block |
| `invalid` | The JSON breaks the schema as written, a moved constraint for instance. `$e->errors` lists each problem with its path, such as `$.seats: should be at most 500` |

## Arrays, streams and token counts

`parse()` takes a schema array as well as a class, and returns the decoded value once it passes, with each `enum` or `const` string in the case the schema declares. `Schema::errors($value, $schema)` checks a value yourself, and `Schema::of(Lead::class)` is a class's schema before it's sanitized.

A stream's `parse()` reads the rest of the stream and parses its final message:

```php
$lead = $client->messages()->createStreamed([...])->parse(Lead::class);
```

`countTokens()` takes the same `output_config`, so you can count what the schema adds to a request.

---

For the full list of what a schema can use, see the [structured outputs guide](https://platform.claude.com/docs/en/build-with-claude/structured-outputs).

---

## Table of Contents

- [Introduction](https://mozex.dev/docs/anthropic-php/v1)
- [AI Integration](https://mozex.dev/docs/anthropic-php/v1/ai-integration)
- [Support Us](https://mozex.dev/docs/anthropic-php/v1/support-us)
- [Requirements](https://mozex.dev/docs/anthropic-php/v1/requirements)
- [Changelog](https://mozex.dev/docs/anthropic-php/v1/changelog)
- [Contributing](https://mozex.dev/docs/anthropic-php/v1/contributing)
- [Questions & Issues](https://mozex.dev/docs/anthropic-php/v1/questions-and-issues)
- [About Mozex](https://mozex.dev/docs/anthropic-php/v1/about)

### Usage

- [Messages](https://mozex.dev/docs/anthropic-php/v1/usage/messages)
- [Streaming](https://mozex.dev/docs/anthropic-php/v1/usage/streaming)
- [Structured Output](https://mozex.dev/docs/anthropic-php/v1/usage/structured-output)
- [Tool Use](https://mozex.dev/docs/anthropic-php/v1/usage/tool-use)
- [Thinking](https://mozex.dev/docs/anthropic-php/v1/usage/thinking)
- [Server Tools](https://mozex.dev/docs/anthropic-php/v1/usage/server-tools)
- [Citations](https://mozex.dev/docs/anthropic-php/v1/usage/citations)
- [Token Counting](https://mozex.dev/docs/anthropic-php/v1/usage/token-counting)
- [Models](https://mozex.dev/docs/anthropic-php/v1/usage/models)
- [Batches](https://mozex.dev/docs/anthropic-php/v1/usage/batches)
- [Completions](https://mozex.dev/docs/anthropic-php/v1/usage/completions)
- [Files](https://mozex.dev/docs/anthropic-php/v1/usage/files)
- [Raw Requests](https://mozex.dev/docs/anthropic-php/v1/usage/raw-requests)

### Reference

- [Configuration](https://mozex.dev/docs/anthropic-php/v1/reference/configuration)
- [Error Handling](https://mozex.dev/docs/anthropic-php/v1/reference/error-handling)
- [Meta Information](https://mozex.dev/docs/anthropic-php/v1/reference/meta-information)
- [Testing](https://mozex.dev/docs/anthropic-php/v1/reference/testing)