SPB Git

Repository Public

php.md 9.3 KB 249 lines markdown

1---2title: PHP SDK3url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/php4description: Install and configure the Anthropic PHP SDK with value objects and builder patterns5---67The Anthropic PHP library provides convenient access to the Claude API from any PHP 8.1.0+ application.89<Info>10  The PHP SDK is currently in beta. APIs might change between versions.11</Info>1213<Info>14  For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers PHP-specific SDK features and configuration.15</Info>1617## Installation1819The SDK uses [PSR-18](https://www.php-fig.org/psr/psr-18/) for HTTP and discovers any installed PSR-18 client automatically. [Guzzle](https://docs.guzzlephp.org/) is recommended because the SDK configures it for streaming with no additional setup:2021```bash22composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7"23```2425## Requirements2627PHP 8.1.0 or higher.2829## Usage3031This library uses named parameters to specify optional arguments. Parameters with a default value must be set by name.3233```php34$client = new Client();3536$message = $client->messages->create(37  maxTokens: 1024,38  messages: [['role' => 'user', 'content' => 'Hello, Claude']],39  model: 'claude-opus-5',40);4142$textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');43echo $textBlock->text;44```4546For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK.4748## Value objects4950It is recommended to use the static `with` constructor `Base64ImageSource::with(data: "U3RhaW5sZXNzIHJvY2tz", ...)` and named parameters to initialize value objects.5152However, builders are also provided `(new Base64ImageSource)->withData("U3RhaW5sZXNzIHJvY2tz")`.5354## Streaming5556The SDK provides support for streaming responses using Server-Sent Events (SSE).5758```php59$client = new Client();6061$stream = $client->messages->createStream(62  maxTokens: 1024,63  messages: [['role' => 'user', 'content' => 'Hello, Claude']],64  model: 'claude-opus-5',65);6667foreach ($stream as $event) {68  echo $event->type . PHP_EOL;69}70```7172Streaming requires an HTTP client that returns the response body incrementally. When Guzzle is the discovered PSR-18 client, the SDK configures it for streaming automatically. With a buffering client, the `foreach` loop yields every event at once when the response completes instead of incrementally; if you observe that symptom, install Guzzle or supply a streaming-capable PSR-18 client through the `streamingTransporter` request option:7374```php75$client = new Anthropic\Client(76  requestOptions: Anthropic\RequestOptions::with(streamingTransporter: $myStreamingClient),77);78```7980## Error handling8182When the library is unable to connect to the API, or if the API returns a non-success status code (that is, a 4xx or 5xx response), a subclass of `Anthropic\Core\Exceptions\APIException` is thrown:8384```php85<?php86// ...87use Anthropic\Core\Exceptions\APIConnectionException;88use Anthropic\Core\Exceptions\APIStatusException;89use Anthropic\Core\Exceptions\RateLimitException;90// ...91try {92  $message = $client->messages->create(93    maxTokens: 1024,94    messages: [['role' => 'user', 'content' => 'Hello, Claude']],95    model: 'claude-opus-5',96  );97} catch (APIConnectionException $e) {98  echo "The server could not be reached", PHP_EOL;99  echo $e->getPrevious()?->getMessage(), PHP_EOL;100} catch (RateLimitException $_) {101  echo "A 429 status code was received; we should back off a bit.", PHP_EOL;102} catch (APIStatusException $e) {103  echo "Another non-200-range status code was received", PHP_EOL;104  echo $e->getMessage();105}106```107108Error codes are as follows:109110| Cause            | Error Type                     |111| ---------------- | ------------------------------ |112| HTTP 400         | `BadRequestException`          |113| HTTP 401         | `AuthenticationException`      |114| HTTP 403         | `PermissionDeniedException`    |115| HTTP 404         | `NotFoundException`            |116| HTTP 409         | `ConflictException`            |117| HTTP 422         | `UnprocessableEntityException` |118| HTTP 429         | `RateLimitException`           |119| HTTP >= 500      | `InternalServerException`      |120| Other HTTP error | `APIStatusException`           |121| Timeout          | `APITimeoutException`          |122| Network error    | `APIConnectionException`       |123124## Retries125126Certain errors are automatically retried two times by default, with a short exponential backoff.127128Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts are all retried by default.129130You can use the `maxRetries` option to configure or disable this:131132```php133use Anthropic\RequestOptions;134// ...135// Configure the default for all requests:136$client = new Client(requestOptions: RequestOptions::with(maxRetries: 0));137138// Or, configure per-request:139$result = $client->messages->create(140  maxTokens: 1024,141  messages: [['role' => 'user', 'content' => 'Hello, Claude']],142  model: 'claude-opus-5',143  requestOptions: RequestOptions::with(maxRetries: 5),144);145```146147## Pagination148149List methods in the Claude API are paginated.150151This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:152153```php154$client = new Client();155156$page = $client->beta->messages->batches->list(limit: 20);157158// fetch items from the current page159foreach ($page->getItems() as $item) {160  echo $item->id, PHP_EOL;161}162// make additional network requests to fetch items from all pages, including and after the current page163foreach ($page->pagingEachItem() as $item) {164  echo $item->id, PHP_EOL;165}166```167168## Advanced usage169170### Undocumented properties171172You can send undocumented parameters to any endpoint, and read undocumented response properties, as follows:173174<Note>175  The `extra*` parameters of the same name override the documented parameters.176</Note>177178```php179<?php180// ...181use Anthropic\RequestOptions;182// ...183$message = $client->messages->create(184  maxTokens: 1024,185  messages: [['role' => 'user', 'content' => 'Hello, Claude']],186  model: 'claude-opus-5',187  requestOptions: RequestOptions::with(188    extraQueryParams: ['my_query_parameter' => 'value'],189    extraBodyParams: ['my_body_parameter' => 'value'],190    extraHeaders: ['my-header' => 'value'],191  ),192);193```194195### Undocumented request parameters196197If you want to explicitly send an extra parameter, you can do so with the `extraQueryParams`, `extraBodyParams`, and `extraHeaders` options under `RequestOptions::with()` when making a request, as seen in the preceding example.198199### Undocumented endpoints200201To make requests to undocumented endpoints while retaining the benefit of authentication, retries, and other client features, you can make requests using `client->request`, as follows:202203```php204$client = new Client();205206$response = $client->request(207  method: "post",208  path: '/undocumented/endpoint',209  query: ['dog' => 'woof'],210  headers: ['useful-header' => 'interesting-value'],211  body: ['hello' => 'world']212);213```214215## Platform integrations216217<Note>218  For detailed platform setup guides with code examples, see:219220  * [Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock)221  * [Amazon Bedrock (Opus 4.6 and earlier)](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy)222  * [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws)223  * [Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai)224  * [Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry)225</Note>226227The PHP SDK supports the following platforms:228229* **Agent Platform:** `Anthropic\Vertex\Client`. Use `::fromEnvironment()`.230* **Bedrock:** `Anthropic\Bedrock\MantleClient`. Use `new MantleClient(awsRegion: ...)`.231* **Bedrock (legacy):** `Anthropic\Bedrock\Client`. Use `::fromEnvironment()` or `::withCredentials()`.232* **Claude Platform on AWS:** `Anthropic\Aws\Client` (requires `aws/aws-sdk-php` as a soft dependency). Use `new Anthropic\Aws\Client(workspaceId: ...)` or set `ANTHROPIC_AWS_WORKSPACE_ID`. Available in beta.233* **Foundry:** `Anthropic\Foundry\Client`. Use `::withCredentials()`.234235Use `MantleClient` for new projects; `Anthropic\Bedrock\Client` remains for existing applications using the Bedrock `InvokeModel` API.236237## Semantic versioning238239This package follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions. As the library is in initial development and has a major version of `0`, APIs might change at any time.240241This package considers improvements to the (non-runtime) PHPDoc type definitions to be non-breaking changes.242243## Additional resources244245* [GitHub repository](https://github.com/anthropics/anthropic-sdk-php)246* [Packagist](https://packagist.org/packages/anthropic-ai/sdk)247* [API reference](https://platform.claude.com/docs/en/api/overview)248* [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming)249
Files main
Menu

Theme