← Blog

Claude API PHP SDK Integration Tutorial

2026-11-15 · 5 min read · SubToAPI Team

If you're searching for a Claude API PHP SDK, here's the short answer: Anthropic doesn't publish an official PHP SDK. They officially support Python and TypeScript/JavaScript, and everything else — including PHP — has to talk to the API over plain HTTPS. That's not actually a problem. Claude's API is a straightforward REST interface, and PHP has mature HTTP tooling (Guzzle, cURL, Symfony HttpClient) that makes integration a non-issue once you know the request shape.

This tutorial covers two paths: calling the Anthropic API directly from PHP with Guzzle, and using a wrapped API like SubToAPI when you want application-scoped keys, usage metadata, and team billing without building that layer yourself. Both approaches use the same underlying request/response pattern, so the code below transfers regardless of which backend you point it at.

Why there's no official Claude API PHP SDK

Anthropic maintains SDKs for the languages with the largest share of AI application development right now — Python for data/ML teams, TypeScript for web and Node backends. PHP, despite powering a huge share of production web apps (Laravel, Symfony, WordPress plugins), isn't on that list. Community SDKs exist on Packagist, but they're unofficial, often lag behind API changes, and vary in maintenance quality.

For production code, the safer bet is to call the HTTP API directly with a well-tested client like Guzzle. You get full control over headers, retries, and timeouts, and you're never blocked waiting for a third-party package to catch up to a new Claude model or feature.

Setting up the PHP environment

Install Guzzle via Composer:

composer require guzzlehttp/guzzle

Store your API key as an environment variable, never hardcoded:

export CLAUDE_API_KEY="your-key-here"

Making a basic request

Here's a minimal PHP class that sends a message to Claude and returns the text response:

<?php

use GuzzleHttp\Client;

class ClaudeClient
{
    private Client $http;
    private string $apiKey;

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->http = new Client([
            'base_uri' => 'https://api.anthropic.com/v1/',
            'timeout'  => 30,
        ]);
    }

    public function sendMessage(string $prompt, string $model = 'claude-sonnet-4'): string
    {
        $response = $this->http->post('messages', [
            'headers' => [
                'x-api-key'         => $this->apiKey,
                'anthropic-version' => '2023-06-01',
                'content-type'      => 'application/json',
            ],
            'json' => [
                'model'      => $model,
                'max_tokens' => 1024,
                'messages'   => [
                    ['role' => 'user', 'content' => $prompt],
                ],
            ],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['content'][0]['text'] ?? '';
    }
}

$client = new ClaudeClient(getenv('CLAUDE_API_KEY'));
echo $client->sendMessage('Summarize the plot of Hamlet in two sentences.');

This pattern — a thin wrapper class around Guzzle — is effectively what an SDK would give you, minus the maintenance burden of someone else's package.

Handling streaming responses

Streaming is where PHP integrations get trickier, since Guzzle needs to be told not to buffer the full response before returning it. Use sink or a streaming body with stream => true:

$response = $this->http->post('messages', [
    'headers' => [
        'x-api-key'         => $this->apiKey,
        'anthropic-version' => '2023-06-01',
        'content-type'      => 'application/json',
    ],
    'json' => [
        'model'      => 'claude-sonnet-4',
        'max_tokens' => 1024,
        'stream'     => true,
        'messages'   => [['role' => 'user', 'content' => $prompt]],
    ],
    'stream' => true,
]);

$body = $response->getBody();
while (!$body->eof()) {
    $chunk = $body->read(1024);
    // Parse server-sent event lines starting with "data: "
    foreach (explode("\n", $chunk) as $line) {
        if (str_starts_with($line, 'data: ')) {
            echo substr($line, 6);
        }
    }
}

In a PHP-FPM setup behind Nginx, make sure output buffering is disabled (ob_flush() + flush()) if you're streaming tokens to a browser via SSE, otherwise the client won't see incremental output.

Tool use and structured output

Claude's tool-calling (function calling) works the same way in PHP as any other language — you define a JSON schema for each tool, pass it in the request, and parse tool_use blocks from the response:

$response = $this->http->post('messages', [
    'headers' => [/* same as above */],
    'json' => [
        'model'      => 'claude-sonnet-4',
        'max_tokens' => 1024,
        'tools' => [[
            'name' => 'get_weather',
            'description' => 'Get current weather for a city',
            'input_schema' => [
                'type' => 'object',
                'properties' => [
                    'city' => ['type' => 'string'],
                ],
                'required' => ['city'],
            ],
        ]],
        'messages' => [['role' => 'user', 'content' => 'What is the weather in Lisbon?']],
    ],
]);

$data = json_decode($response->getBody()->getContents(), true);
foreach ($data['content'] as $block) {
    if ($block['type'] === 'tool_use') {
        // $block['input'] contains the parsed arguments
        var_dump($block['input']);
    }
}

Using SubToAPI instead of direct Anthropic keys

If you're building a product that needs per-application API keys, usage metadata, team seats, or just want a dashboard instead of raw billing invoices, SubToAPI sits between your PHP app and Claude without changing the request shape above — you swap the base URL and key:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello from PHP"}]
  }'

Everything in the PHP examples above — streaming, tool use, message formatting — works identically against this endpoint. The practical benefit is that you get a sub_live_... key scoped to one app, visibility into token usage per key, and team member access without wiring up your own billing and auth layer. Check /docs/quickstart for setup and /docs/streaming and /docs/tools for the streaming and function-calling specifics. There's a free trial at /signup if you want to test it against your existing PHP codebase before committing to a plan — see /pricing for the Solo, Team, and Scale tiers.

Best practices for PHP integrations

Questions

Does Anthropic offer an official PHP SDK for Claude? No. Anthropic officially supports Python and TypeScript SDKs. PHP integrations call the REST API directly, typically through Guzzle or cURL.

Can I use Laravel with the Claude API? Yes. Wrap the Guzzle calls in a Laravel service class or use Laravel's built-in Http facade, which is a thin wrapper around Guzzle and works with the same request structure shown above.

Is streaming Claude responses in PHP harder than in Node or Python? It requires more manual handling since PHP isn't natively async, but it's fully supported — disable output buffering, read the response body in chunks, and parse server-sent events line by line as shown above.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →