Skip to content

Appendix A: API Reference Quick Guide

Complete reference for the Claude API with PHP examples. Bookmark this page for quick access to endpoints, parameters, and response formats.


Table of Contents


Base Configuration

API Endpoint

https://api.anthropic.com/v1/messages

Authentication Header

php
# filename: auth-header.php
'x-api-key' => 'your_api_key_here'

Required Headers

php
# filename: required-headers.php
$headers = [
    'x-api-key' => getenv('ANTHROPIC_API_KEY'),
    'anthropic-version' => '2023-06-01',
    'content-type' => 'application/json',
];

Optional Headers

php
# filename: optional-headers.php
// Beta features
'anthropic-beta' => 'prompt-caching-2024-07-31'

// Custom identifier for your integration
'anthropic-client-id' => 'your-client-id'

PHP SDK Initialization

php
# filename: sdk-initialization.php
use Anthropic\Anthropic;

$client = Anthropic::factory()
    ->withApiKey(getenv('ANTHROPIC_API_KEY'))
    ->withHttpHeader('anthropic-version', '2023-06-01')
    ->make();

Messages API

Create Message (Basic)

Endpoint: POST /v1/messages

Minimal Request:

php
# filename: minimal-request.php
$response = $client->messages()->create([
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 1024,
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, Claude!']
    ]
]);

Complete Request with All Options:

php
# filename: complete-request.php
$response = $client->messages()->create([
    // Required parameters
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 4096,
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Analyze this code and suggest improvements.'
        ]
    ],

    // Optional parameters
    'system' => 'You are an expert PHP developer and code reviewer.',
    'temperature' => 0.7,
    'top_p' => 0.9,
    'top_k' => 40,
    'stop_sequences' => ['</code>', 'END'],
    'metadata' => [
        'user_id' => 'user_12345'
    ],

    // Streaming
    'stream' => false,
]);

Multi-turn Conversation:

php
# filename: multi-turn-conversation.php
$response = $client->messages()->create([
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 1024,
    'messages' => [
        [
            'role' => 'user',
            'content' => 'What is dependency injection?'
        ],
        [
            'role' => 'assistant',
            'content' => 'Dependency injection is a design pattern...'
        ],
        [
            'role' => 'user',
            'content' => 'Show me a PHP example.'
        ]
    ]
]);

Request Parameters

Required Parameters

ParameterTypeDescriptionExample
modelstringModel identifier"claude-sonnet-4-20250514"
max_tokensintegerMaximum tokens to generate (1-4096)1024
messagesarrayArray of message objectsSee examples

Optional Parameters

ParameterTypeDefaultDescription
systemstringnullSystem prompt that defines behavior
temperaturefloat1.0Randomness (0.0-1.0)
top_pfloat-1Nucleus sampling threshold
top_kinteger-1Top-k sampling parameter
stop_sequencesarray[]Sequences that stop generation
streambooleanfalseEnable streaming responses
metadataobject{}Custom metadata for request
toolsarray[]Available tools for function calling
tool_choiceobjectautoHow to use tools

Message Object Structure

php
# filename: message-structure.php
[
    'role' => 'user',      // Required: 'user' or 'assistant'
    'content' => 'text'    // Required: string or array of content blocks
]

Content Block Types:

php
# filename: content-blocks.php
// Text content
['type' => 'text', 'text' => 'Your message here']

// Image content (base64)
[
    'type' => 'image',
    'source' => [
        'type' => 'base64',
        'media_type' => 'image/jpeg',
        'data' => base64_encode($imageData)
    ]
]

// Image content (URL)
[
    'type' => 'image',
    'source' => [
        'type' => 'url',
        'url' => 'https://example.com/image.jpg'
    ]
]

// Tool use (assistant message)
[
    'type' => 'tool_use',
    'id' => 'toolu_12345',
    'name' => 'get_weather',
    'input' => ['city' => 'San Francisco']
]

// Tool result (user message)
[
    'type' => 'tool_result',
    'tool_use_id' => 'toolu_12345',
    'content' => 'Temperature: 72°F, Sunny'
]

Response Format

Standard Response

php
# filename: standard-response.php
// Response object structure
$response = [
    'id' => 'msg_01AbCdEfGhIjKlMnOpQr',
    'type' => 'message',
    'role' => 'assistant',
    'content' => [
        [
            'type' => 'text',
            'text' => 'Hello! How can I help you today?'
        ]
    ],
    'model' => 'claude-sonnet-4-20250514',
    'stop_reason' => 'end_turn',
    'stop_sequence' => null,
    'usage' => [
        'input_tokens' => 12,
        'output_tokens' => 25
    ]
];

// Accessing response text
$text = $response->content[0]->text;

// Accessing usage
$inputTokens = $response->usage->input_tokens;
$outputTokens = $response->usage->output_tokens;

Stop Reasons

Stop ReasonDescription
end_turnNatural conversation end
max_tokensHit max_tokens limit
stop_sequenceHit a stop sequence
tool_useClaude wants to use a tool

Response with Tool Use

php
# filename: tool-use-response.php
$response = [
    'id' => 'msg_01AbCdEfGhIjKlMnOpQr',
    'type' => 'message',
    'role' => 'assistant',
    'content' => [
        [
            'type' => 'text',
            'text' => "I'll check the weather for you."
        ],
        [
            'type' => 'tool_use',
            'id' => 'toolu_01ABC',
            'name' => 'get_weather',
            'input' => [
                'city' => 'San Francisco',
                'units' => 'fahrenheit'
            ]
        ]
    ],
    'stop_reason' => 'tool_use',
    'usage' => [
        'input_tokens' => 250,
        'output_tokens' => 45
    ]
];

Streaming Responses

Enable Streaming

php
# filename: streaming-example.php
$stream = $client->messages()->createStreamed([
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 1024,
    'messages' => [
        ['role' => 'user', 'content' => 'Write a haiku about PHP']
    ]
]);

foreach ($stream as $event) {
    if ($event->type === 'content_block_delta') {
        echo $event->delta->text;
    }
}

Stream Event Types

Event TypeDescriptionData
message_startStream startedMessage metadata
content_block_startContent block startedBlock index and type
content_block_deltaPartial contentDelta with text
content_block_stopContent block finishedBlock index
message_deltaMessage metadata updateUsage, stop_reason
message_stopStream endedNone
pingKeepaliveNone
errorError occurredError details

Stream Event Examples

php
# filename: stream-events.php
// message_start
[
    'type' => 'message_start',
    'message' => [
        'id' => 'msg_01ABC',
        'type' => 'message',
        'role' => 'assistant',
        'content' => [],
        'model' => 'claude-sonnet-4-20250514',
        'usage' => ['input_tokens' => 12, 'output_tokens' => 0]
    ]
]

// content_block_delta
[
    'type' => 'content_block_delta',
    'index' => 0,
    'delta' => [
        'type' => 'text_delta',
        'text' => 'Hello'
    ]
]

// message_delta
[
    'type' => 'message_delta',
    'delta' => [
        'stop_reason' => 'end_turn',
        'stop_sequence' => null
    ],
    'usage' => ['output_tokens' => 25]
]

Tool Use (Function Calling)

Define Tools

php
# filename: define-tools.php
$tools = [
    [
        'name' => 'get_weather',
        'description' => 'Get current weather for a city',
        'input_schema' => [
            'type' => 'object',
            'properties' => [
                'city' => [
                    'type' => 'string',
                    'description' => 'City name'
                ],
                'units' => [
                    'type' => 'string',
                    'enum' => ['celsius', 'fahrenheit'],
                    'description' => 'Temperature units'
                ]
            ],
            'required' => ['city']
        ]
    ],
    [
        'name' => 'search_database',
        'description' => 'Search database for records',
        'input_schema' => [
            'type' => 'object',
            'properties' => [
                'query' => [
                    'type' => 'string',
                    'description' => 'Search query'
                ],
                'limit' => [
                    'type' => 'integer',
                    'description' => 'Maximum results',
                    'default' => 10
                ]
            ],
            'required' => ['query']
        ]
    ]
];

$response = $client->messages()->create([
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 1024,
    'tools' => $tools,
    'messages' => [
        ['role' => 'user', 'content' => 'What is the weather in Paris?']
    ]
]);

Tool Choice Options

php
# filename: tool-choice-options.php
// Auto (default) - Let Claude decide
'tool_choice' => ['type' => 'auto']

// Force a specific tool
'tool_choice' => [
    'type' => 'tool',
    'name' => 'get_weather'
]

// Require any tool
'tool_choice' => ['type' => 'any']

Handle Tool Use Response

php
# filename: handle-tool-use.php
// Check if Claude wants to use a tool
foreach ($response->content as $block) {
    if ($block->type === 'tool_use') {
        $toolName = $block->name;
        $toolInput = $block->input;
        $toolUseId = $block->id;

        // Execute the tool
        $result = executeTool($toolName, $toolInput);

        // Send result back to Claude
        $followUp = $client->messages()->create([
            'model' => 'claude-sonnet-4-20250514',
            'max_tokens' => 1024,
            'tools' => $tools,
            'messages' => [
                ['role' => 'user', 'content' => 'What is the weather in Paris?'],
                ['role' => 'assistant', 'content' => $response->content],
                [
                    'role' => 'user',
                    'content' => [
                        [
                            'type' => 'tool_result',
                            'tool_use_id' => $toolUseId,
                            'content' => json_encode($result)
                        ]
                    ]
                ]
            ]
        ]);
    }
}

Vision API

Send Image (Base64)

php
# filename: send-image-base64.php
$imageData = file_get_contents('image.jpg');
$base64Image = base64_encode($imageData);

$response = $client->messages()->create([
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 1024,
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'image',
                    'source' => [
                        'type' => 'base64',
                        'media_type' => 'image/jpeg',
                        'data' => $base64Image
                    ]
                ],
                [
                    'type' => 'text',
                    'text' => 'What is in this image?'
                ]
            ]
        ]
    ]
]);

Send Image (URL)

php
# filename: send-image-url.php
$response = $client->messages()->create([
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 1024,
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'image',
                    'source' => [
                        'type' => 'url',
                        'url' => 'https://example.com/image.jpg'
                    ]
                ],
                [
                    'type' => 'text',
                    'text' => 'Describe this image in detail.'
                ]
            ]
        ]
    ]
]);

Supported Image Formats

FormatMIME TypeMax Size
JPEGimage/jpeg5 MB
PNGimage/png5 MB
GIFimage/gif5 MB
WebPimage/webp5 MB

Structured Outputs

Structured outputs allow you to enforce JSON schema validation on Claude's responses, ensuring consistent, type-safe data structures.

Enable Structured Outputs

php
# filename: structured-outputs.php
$response = $client->messages()->create([
    'model' => 'claude-sonnet-4-20250514',
    'max_tokens' => 1024,
    'messages' => [
        ['role' => 'user', 'content' => 'Extract user information from this text: "John Doe, age 30, email: john@example.com"']
    ],
    'response_format' => [
        'type' => 'json_schema',
        'json_schema' => [
            'name' => 'user_extraction',
            'strict' => true,
            'schema' => [
                'type' => 'object',
                'properties' => [
                    'name' => [
                        'type' => 'string',
                        'description' => 'User full name'
                    ],
                    'age' => [
                        'type' => 'integer',
                        'description' => 'User age'
                    ],
                    'email' => [
                        'type' => 'string',
                        'format' => 'email',
                        'description' => 'User email address'
                    ]
                ],
                'required' => ['name', 'age', 'email'],
                'additionalProperties' => false
            ]
        ]
    ]
]);

// Response content will be valid JSON matching the schema
$userData = json_decode($response->content[0]->text, true);

Schema Definition

php
# filename: structured-schema-example.php
$schema = [
    'type' => 'object',
    'properties' => [
        'products' => [
            'type' => 'array',
            'items' => [
                'type' => 'object',
                'properties' => [
                    'name' => ['type' => 'string'],
                    'price' => ['type' => 'number'],
                    'in_stock' => ['type' => 'boolean']
                ],
                'required' => ['name', 'price']
            ]
        ],
        'total' => ['type' => 'number']
    ],
    'required' => ['products', 'total']
];

Error Handling for Structured Outputs

php
# filename: structured-outputs-error-handling.php
try {
    $response = $client->messages()->create([
        'model' => 'claude-sonnet-4-20250514',
        'max_tokens' => 1024,
        'messages' => [
            ['role' => 'user', 'content' => 'Extract data...']
        ],
        'response_format' => [
            'type' => 'json_schema',
            'json_schema' => $schema
        ]
    ]);

    $data = json_decode($response->content[0]->text, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new RuntimeException('Invalid JSON response: ' . json_last_error_msg());
    }
} catch (ErrorException $e) {
    // Handle API errors
    if ($e->getErrorType() === 'invalid_request_error') {
        // Schema might be invalid
        error_log('Schema validation failed: ' . $e->getMessage());
    }
}

Note: Structured outputs are available on Claude Sonnet 4.5 and Opus 4.1 models.


Error Responses

Error Response Structure

php
# filename: error-response.php
[
    'type' => 'error',
    'error' => [
        'type' => 'invalid_request_error',
        'message' => 'max_tokens: Field required'
    ]
]

Common Error Types

Error TypeHTTP StatusDescriptionSolution
invalid_request_error400Malformed requestCheck request parameters
authentication_error401Invalid API keyVerify API key
permission_error403No access to resourceCheck account permissions
not_found_error404Resource not foundVerify endpoint URL
rate_limit_error429Too many requestsImplement rate limiting
api_error500Server errorRetry with backoff
overloaded_error529Service overloadedRetry with backoff

Error Handling Example

php
# filename: error-handling.php
use Anthropic\Exceptions\AnthropicException;
use Anthropic\Exceptions\ErrorException;

try {
    $response = $client->messages()->create([
        'model' => 'claude-sonnet-4-20250514',
        'max_tokens' => 1024,
        'messages' => [
            ['role' => 'user', 'content' => 'Hello!']
        ]
    ]);
} catch (ErrorException $e) {
    $errorType = $e->getErrorType();
    $errorMessage = $e->getMessage();

    match($errorType) {
        'rate_limit_error' => handleRateLimit($e),
        'invalid_request_error' => logInvalidRequest($e),
        'authentication_error' => refreshApiKey($e),
        default => logError($e)
    };
}

Rate Limits

Rate Limit Headers

php
# filename: rate-limit-headers.php
// Check remaining requests
$remaining = $response->headers['anthropic-ratelimit-requests-remaining'];
$limit = $response->headers['anthropic-ratelimit-requests-limit'];
$reset = $response->headers['anthropic-ratelimit-requests-reset'];

// Check remaining tokens
$tokensRemaining = $response->headers['anthropic-ratelimit-tokens-remaining'];
$tokensLimit = $response->headers['anthropic-ratelimit-tokens-limit'];
$tokensReset = $response->headers['anthropic-ratelimit-tokens-reset'];

Default Rate Limits (Tier 1)

Limit TypeClaude OpusClaude SonnetClaude Haiku
Requests/min505050
Tokens/min40,00040,00040,000
Tokens/day1,000,0001,000,0001,000,000

Note: Limits increase with higher tiers. Check console.anthropic.com for your tier.

Handle Rate Limiting

php
# filename: rate-limiting-handler.php
function makeRequestWithRetry($client, $params, $maxRetries = 3) {
    $attempt = 0;

    while ($attempt < $maxRetries) {
        try {
            return $client->messages()->create($params);
        } catch (ErrorException $e) {
            if ($e->getErrorType() === 'rate_limit_error') {
                $attempt++;
                $waitTime = min(pow(2, $attempt) * 1000000, 32000000);
                usleep($waitTime);
                continue;
            }
            throw $e;
        }
    }

    throw new Exception('Max retries exceeded');
}

Model Versions

Current Models (2024)

ModelIdentifierContextUse Case
Claude Opus 4claude-opus-4-20250514200K tokensMost capable, complex tasks
Claude Sonnet 4claude-sonnet-4-20250514200K tokensBalanced performance & cost
Claude Haiku 4.5claude-haiku-4-20250514200K tokensFast, cost-effective

Model Selection Guide

php
# filename: model-selection.php
// Complex reasoning, highest quality
$model = 'claude-opus-4-20250514';

// Balanced - most use cases
$model = 'claude-sonnet-4-20250514';

// High volume, simple tasks
$model = 'claude-haiku-4-20250514';

Model Pricing (Approximate)

ModelInput (per 1M tokens)Output (per 1M tokens)
Opus 4$15.00$75.00
Sonnet 4$3.00$15.00
Haiku 3.5$0.80$4.00

Check official pricing at anthropic.com/pricing for current rates.


Quick Reference: Complete Example

php
# filename: complete-example.php
<?php
require 'vendor/autoload.php';

use Anthropic\Anthropic;
use Anthropic\Exceptions\ErrorException;

// Initialize client
$client = Anthropic::factory()
    ->withApiKey(getenv('ANTHROPIC_API_KEY'))
    ->make();

// Define tools
$tools = [
    [
        'name' => 'calculate',
        'description' => 'Perform mathematical calculation',
        'input_schema' => [
            'type' => 'object',
            'properties' => [
                'expression' => [
                    'type' => 'string',
                    'description' => 'Mathematical expression to evaluate'
                ]
            ],
            'required' => ['expression']
        ]
    ]
];

try {
    // Make request
    $response = $client->messages()->create([
        'model' => 'claude-sonnet-4-20250514',
        'max_tokens' => 1024,
        'system' => 'You are a helpful assistant.',
        'temperature' => 0.7,
        'tools' => $tools,
        'messages' => [
            [
                'role' => 'user',
                'content' => 'What is 25 * 47?'
            ]
        ]
    ]);

    // Process response
    foreach ($response->content as $block) {
        if ($block->type === 'text') {
            echo $block->text . "\n";
        } elseif ($block->type === 'tool_use') {
            echo "Tool: {$block->name}\n";
            echo "Input: " . json_encode($block->input) . "\n";
        }
    }

    // Log usage
    echo "\nTokens used: {$response->usage->input_tokens} in, ";
    echo "{$response->usage->output_tokens} out\n";

} catch (ErrorException $e) {
    echo "Error: {$e->getMessage()}\n";
    echo "Type: {$e->getErrorType()}\n";
}

Additional Resources


Quick Navigation

Last updated: November 2024 • API Version: 2023-06-01