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.



https://api.anthropic.com/v1/messages
auth-header.php
'x-api-key' => 'your_api_key_here'
required-headers.php
$headers = [
'x-api-key' => getenv('ANTHROPIC_API_KEY'),
'anthropic-version' => '2023-06-01',
'content-type' => 'application/json',
];
optional-headers.php
use ClaudePhp\ClaudePhp;
// Beta features
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY'),
betaFeatures: ['prompt-caching-2024-07-31']
);
// Custom identifier for your integration
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY'),
clientId: 'your-client-id'
);
sdk-initialization.php
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY'),
anthropicVersion: '2023-06-01'
);

Endpoint: POST /v1/messages

Minimal Request:

minimal-request.php
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'max_tokens' => 1024,
'messages' => [
['role' => 'user', 'content' => 'Hello, Claude!']
]
]);

Complete Request with All Options:

complete-request.php
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$response = $client->messages()->create([
// Required parameters
'model' => 'claude-sonnet-4-5-20250929',
'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:

multi-turn-conversation.php
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'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.'
]
]
]);

ParameterTypeDescriptionExample
modelstringModel identifier"claude-sonnet-4-5-20250929"
max_tokensintegerMaximum tokens to generate (1-4096)1024
messagesarrayArray of message objectsSee examples
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-structure.php
[
'role' => 'user', // Required: 'user' or 'assistant'
'content' => 'text' // Required: string or array of content blocks
]

Content Block Types:

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'
]

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-5-20250929',
'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 ReasonDescription
end_turnNatural conversation end
max_tokensHit max_tokens limit
stop_sequenceHit a stop sequence
tool_useClaude wants to use a tool
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-example.php
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$stream = $client->messages()->createStreamed([
'model' => 'claude-sonnet-4-5-20250929',
'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;
}
}
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-events.php
// message_start
[
'type' => 'message_start',
'message' => [
'id' => 'msg_01ABC',
'type' => 'message',
'role' => 'assistant',
'content' => [],
'model' => 'claude-sonnet-4-5-20250929',
'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]
]

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']
]
]
];
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'max_tokens' => 1024,
'tools' => $tools,
'messages' => [
['role' => 'user', 'content' => 'What is the weather in Paris?']
]
]);
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.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-5-20250929',
'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)
]
]
]
]
]);
}
}

send-image-base64.php
use ClaudePhp\ClaudePhp;
$imageData = file_get_contents('image.jpg');
$base64Image = base64_encode($imageData);
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'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
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'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.'
]
]
]
]
]);
FormatMIME TypeMax Size
JPEGimage/jpeg5 MB
PNGimage/png5 MB
GIFimage/gif5 MB
WebPimage/webp5 MB

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

structured-outputs.php
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'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);
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']
];
structured-outputs-error-handling.php
try {
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'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-response.php
[
'type' => 'error',
'error' => [
'type' => 'invalid_request_error',
'message' => 'max_tokens: Field required'
]
]
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.php
use ClaudePhp\Exceptions\ClaudeException;
use ClaudePhp\Exceptions\ErrorException;
try {
$response = $client->messages()->create([
'model' => 'claude-sonnet-4-5-20250929',
'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-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'];
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.

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');
}

ModelIdentifierContextUse Case
Claude Opus 4claude-opus-4-20250514200K tokensMost capable, complex tasks
Claude Sonnet 4.5claude-sonnet-4-5-20250929200K tokensBalanced performance & cost
Claude Haiku 4.5claude-haiku-4-5-20251001200K tokensFast, cost-effective
model-selection.php
// Complex reasoning, highest quality
$model = 'claude-opus-4-20250514';
// Balanced - most use cases
$model = 'claude-sonnet-4-5-20250929';
// High volume, simple tasks
$model = 'claude-haiku-4-5-20251001';
ModelInput (per 1M tokens)Output (per 1M tokens)
Opus 4$15.00$75.00
Sonnet 4.5$3.00$15.00
Haiku 4.5$1.00$5.00

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


complete-example.php
<?php
require 'vendor/autoload.php';
use ClaudePhp\ClaudePhp;
use ClaudePhp\Exceptions\ErrorException;
// Initialize client
$client = new ClaudePhp(
apiKey: getenv('ANTHROPIC_API_KEY')
);
// 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-5-20250929',
'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";
}


::: tip Quick Navigation

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