Appendix A: API Reference Quick Guide
Appendix A: API Reference Quick Guide
Section titled “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
Section titled “Table of Contents”- Base Configuration
- Messages API
- Request Parameters
- Response Format
- Streaming Responses
- Tool Use (Function Calling)
- Vision API
- Structured Outputs
- Error Responses
- Rate Limits
- Model Versions
Base Configuration
Section titled “Base Configuration”API Endpoint
Section titled “API Endpoint”https://api.anthropic.com/v1/messagesAuthentication Header
Section titled “Authentication Header”'x-api-key' => 'your_api_key_here'Required Headers
Section titled “Required Headers”$headers = [ 'x-api-key' => getenv('ANTHROPIC_API_KEY'), 'anthropic-version' => '2023-06-01', 'content-type' => 'application/json',];Optional Headers
Section titled “Optional Headers”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');PHP SDK Initialization
Section titled “PHP SDK Initialization”use ClaudePhp\ClaudePhp;
$client = new ClaudePhp( apiKey: getenv('ANTHROPIC_API_KEY'), anthropicVersion: '2023-06-01');Messages API
Section titled “Messages API”Create Message (Basic)
Section titled “Create Message (Basic)”Endpoint: POST /v1/messages
Minimal Request:
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:
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:
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.' ] ]]);Request Parameters
Section titled “Request Parameters”Required Parameters
Section titled “Required Parameters”| Parameter | Type | Description | Example |
|---|---|---|---|
model | string | Model identifier | "claude-sonnet-4-5-20250929" |
max_tokens | integer | Maximum tokens to generate (1-4096) | 1024 |
messages | array | Array of message objects | See examples |
Optional Parameters
Section titled “Optional Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
system | string | null | System prompt that defines behavior |
temperature | float | 1.0 | Randomness (0.0-1.0) |
top_p | float | -1 | Nucleus sampling threshold |
top_k | integer | -1 | Top-k sampling parameter |
stop_sequences | array | [] | Sequences that stop generation |
stream | boolean | false | Enable streaming responses |
metadata | object | {} | Custom metadata for request |
tools | array | [] | Available tools for function calling |
tool_choice | object | auto | How to use tools |
Message Object Structure
Section titled “Message Object Structure”[ 'role' => 'user', // Required: 'user' or 'assistant' 'content' => 'text' // Required: string or array of content blocks]Content Block Types:
// 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
Section titled “Response Format”Standard Response
Section titled “Standard Response”// 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 Reasons
Section titled “Stop Reasons”| Stop Reason | Description |
|---|---|
end_turn | Natural conversation end |
max_tokens | Hit max_tokens limit |
stop_sequence | Hit a stop sequence |
tool_use | Claude wants to use a tool |
Response with Tool Use
Section titled “Response with Tool Use”$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
Section titled “Streaming Responses”Enable Streaming
Section titled “Enable Streaming”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; }}Stream Event Types
Section titled “Stream Event Types”| Event Type | Description | Data |
|---|---|---|
message_start | Stream started | Message metadata |
content_block_start | Content block started | Block index and type |
content_block_delta | Partial content | Delta with text |
content_block_stop | Content block finished | Block index |
message_delta | Message metadata update | Usage, stop_reason |
message_stop | Stream ended | None |
ping | Keepalive | None |
error | Error occurred | Error details |
Stream Event Examples
Section titled “Stream Event Examples”// 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]]Tool Use (Function Calling)
Section titled “Tool Use (Function Calling)”Define Tools
Section titled “Define Tools”$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
Section titled “Tool Choice Options”// 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
Section titled “Handle Tool Use Response”// Check if Claude wants to use a toolforeach ($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) ] ] ] ] ]); }}Vision API
Section titled “Vision API”Send Image (Base64)
Section titled “Send Image (Base64)”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)
Section titled “Send Image (URL)”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.' ] ] ] ]]);Supported Image Formats
Section titled “Supported Image Formats”| Format | MIME Type | Max Size |
|---|---|---|
| JPEG | image/jpeg | 5 MB |
| PNG | image/png | 5 MB |
| GIF | image/gif | 5 MB |
| WebP | image/webp | 5 MB |
Structured Outputs
Section titled “Structured Outputs”Structured outputs allow you to enforce JSON schema validation on Claude’s responses, ensuring consistent, type-safe data structures.
Enable Structured Outputs
Section titled “Enable Structured Outputs”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);Schema Definition
Section titled “Schema Definition”$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
Section titled “Error Handling for Structured Outputs”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 Responses
Section titled “Error Responses”Error Response Structure
Section titled “Error Response Structure”[ 'type' => 'error', 'error' => [ 'type' => 'invalid_request_error', 'message' => 'max_tokens: Field required' ]]Common Error Types
Section titled “Common Error Types”| Error Type | HTTP Status | Description | Solution |
|---|---|---|---|
invalid_request_error | 400 | Malformed request | Check request parameters |
authentication_error | 401 | Invalid API key | Verify API key |
permission_error | 403 | No access to resource | Check account permissions |
not_found_error | 404 | Resource not found | Verify endpoint URL |
rate_limit_error | 429 | Too many requests | Implement rate limiting |
api_error | 500 | Server error | Retry with backoff |
overloaded_error | 529 | Service overloaded | Retry with backoff |
Error Handling Example
Section titled “Error Handling Example”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 Limits
Section titled “Rate Limits”Rate Limit Headers
Section titled “Rate Limit Headers”// 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)
Section titled “Default Rate Limits (Tier 1)”| Limit Type | Claude Opus | Claude Sonnet | Claude Haiku |
|---|---|---|---|
| Requests/min | 50 | 50 | 50 |
| Tokens/min | 40,000 | 40,000 | 40,000 |
| Tokens/day | 1,000,000 | 1,000,000 | 1,000,000 |
Note: Limits increase with higher tiers. Check console.anthropic.com for your tier.
Handle Rate Limiting
Section titled “Handle Rate Limiting”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
Section titled “Model Versions”Current Models (2024)
Section titled “Current Models (2024)”| Model | Identifier | Context | Use Case |
|---|---|---|---|
| Claude Opus 4 | claude-opus-4-20250514 | 200K tokens | Most capable, complex tasks |
| Claude Sonnet 4.5 | claude-sonnet-4-5-20250929 | 200K tokens | Balanced performance & cost |
| Claude Haiku 4.5 | claude-haiku-4-5-20251001 | 200K tokens | Fast, cost-effective |
Model Selection Guide
Section titled “Model Selection Guide”// 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';Model Pricing (Approximate)
Section titled “Model Pricing (Approximate)”| Model | Input (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.
Quick Reference: Complete Example
Section titled “Quick Reference: Complete Example”<?phprequire '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";}Additional Resources
Section titled “Additional Resources”- Official API Documentation - Complete API reference
- API Status Page - Service status
- Anthropic Console - Manage API keys
- PHP SDK Repository - SDK source code
- Pricing Calculator - Calculate costs
::: tip Quick Navigation
- ← Appendix A: API Reference - Complete API reference
- Appendix B: Prompting Patterns → - Prompt templates
- Appendix C: Error Codes → - Troubleshooting guide
- Appendix D: Resources → - Tools and resources
- Back to Series - Return to main series :::
Last updated: November 2024 • API Version: 2023-06-01