Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
d031f95
fix: iterate Store search as one page, long timeout for Actor version…
claude Nov 27, 2026
c31388c
fix: address review of Store search docs, deprecation tag, PHPStan le…
claude Nov 27, 2026
6b06fa9
feat!: split Store search from the Store listing, sync with spec v2-2…
claude Dec 3, 2026
cd9b0d0
fix: address review of Store search split, document public URL scope …
claude Dec 3, 2026
2b82662
fix: drop a vacuous build digest assertion that PHPStan reports witho…
claude Dec 3, 2026
54bb3d7
docs: correct the includeInputSchema page size rule and the public UR…
claude Dec 3, 2026
a441a3e
docs: state the includeInputSchema page size rule plainly and rewrap …
claude Dec 3, 2026
07b6188
chore: sync with spec v2-2026-12-03T122505Z
claude Dec 4, 2026
1070e30
feat: add client-wide headers and streamRecord, address full review
claude Dec 4, 2026
d2d8c42
fix: retry opening streams, keep a client-wide Authorization header f…
claude Dec 4, 2026
ec82763
test: use a timeout below the client cap in the streamRecord timeout …
claude Dec 4, 2026
b007bb8
feat: redirect the run log in call() of an Actor and a task, return n…
claude Dec 4, 2026
d39c7ff
test: fix the Actor path and quote style in the log redirection tests
claude Dec 4, 2026
b16d55c
fix: narrow the return type of the broken read handler for PHPStan
claude Dec 4, 2026
bd233dc
fix: bound the log redirection by waitSecs, reopen a stream closed ea…
claude Dec 4, 2026
56a99aa
fix: mark the deadline check as time dependent for PHPStan
claude Dec 4, 2026
f4603af
fix: skip untimestamped lines of a replayed stream, do not open a str…
claude Dec 4, 2026
1d79687
fix: redirect a first line that the first stream was cut inside, test…
claude Dec 4, 2026
844dfb8
fix: replay a cut log stream by byte offset so no line is lost or rep…
claude Dec 4, 2026
1529bab
docs: describe the resume point of a cut log stream as the cut line
claude Dec 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 0.15.0

- Synced with Apify OpenAPI spec `v2-2026-12-03T122505Z`: the API dropped the Store `allowsAgenticUsers` filter.
- **Breaking:** `StoreListOptions` loses `search`, `sortBy`, and `allowsAgenticUsers`. `store()->list()` and `iterate()` browse the Store in Store order.
- Added `store()->search()` with `StoreSearchOptions` and `StoreSearchResult`. It returns the Actors that match a query best as one page of at most 100, since the API ignores `offset` for a search. It rejects an empty query and a limit that is not positive.
- `versions()->create()` and `version()->update()` use the `long` timeout tier by default, since a version can carry its source files.
- Documented the Store `category` filter, the `search` page limit, and the `limit` of at most 10 with `includeInputSchema`.
- Documented that a signed public URL of a dataset or key-value store grants access to all items or keys, and that the options only set the default response.
- Added the `headers` argument of `ApifyClient`, which sends headers with every request (apify/apify-client-js#1058).
- Added `keyValueStore()->streamRecord()`, which reads a record as a stream, and the `$timeoutSecs` argument of `task()->publish()` and `unpublish()`.
- `streamRecord()`, `dataset()->streamItems()`, and `log()->stream()` take `$timeoutSecs` and retry opening the stream like any request.
- `call()` of an Actor and of a task redirects the run log, to the standard error stream by default (new `$log` argument, as in the reference client).
- Added `run()->redirectLog()` and the `$timeoutSecs` argument of `run()->getStreamedLog()`.
- **Breaking:** `log()->stream()` returns `null` for a missing log of a client with an ID.
- A client-wide `Authorization` header is sent as `X-Apify-Authorization` to an Actor server, so the Actor never receives it.
- Corrected the description of `includeUnrunnableActors` and documented the constructor arguments, the transport contract, and the other public methods that the docs missed.
- Raised PHPStan to level 9 and added an integration test for `user($id)->get()`.

## 0.14.1

- Synced with Apify OpenAPI spec `v2-2026-11-18T151559Z`: `UserClient::get()` returns only `plan.availableProxyGroups`, `effectivePlatformFeatures` and `isPaying` for a proxy password.
Expand Down
33 changes: 26 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ $configured = new ApifyClient(
| `timeoutMaxSecs` | `timeoutSecs` | Cap on the timeout of any attempt, per-call overrides, and growth across retries included. |
| `compression` | `null` (brotli, else gzip) | Request body compression: `'brotli'`, `'gzip'`, `'zstd'`, or a custom `HttpCompressorInterface`, see [HTTP compression](#http-compression). |
| `userAgentSuffix` | `null` | Suffix appended to the `User-Agent` header. |
| `httpClient` | Guzzle | The transport, an `Apify\Client\Http\HttpClientInterface`. |
| `headers` | `[]` | Headers sent with every request, for example an integration marker. They replace the built-in `User-Agent` and token headers, and a header a call sets for itself, such as `Content-Type`, replaces them. A client-wide `Authorization` header is sent as `X-Apify-Authorization` to an Actor server, so the Actor never receives it. |
| `httpClient` | Guzzle | The transport, an `Apify\Client\Http\HttpClientInterface`, see [Replaceable HTTP transport](#replaceable-http-transport). |
| `requestFactory` | Guzzle's | The PSR-17 `RequestFactoryInterface` that builds the requests. |
| `streamFactory` | Guzzle's | The PSR-17 `StreamFactoryInterface` that builds the request bodies. |
| `isAtHomeFn` | reads `APIFY_IS_AT_HOME` | A `callable(): bool` that replaces the detection of the `isAtHome` flag of the `User-Agent` header. |

Requests are retried with exponential backoff and jitter on network errors, HTTP 429, and 5xx. Other 4xx
responses throw an `ApifyApiException` subclass for the status. A 404 on a single resource is not thrown:
Expand All @@ -84,7 +88,7 @@ A call that asks the API to hold its response with `waitForFinish` (`RunClient::
`ActorClient::defaultBuild()`, and the `waitForFinish` option of `ActorClient::start()`, `build()` and
`TaskClient::start()`) gets that hold on top of its tier, for at most 60 seconds.

Every request method also takes a trailing `$timeoutSecs` that overrides the tier for that call: seconds, a
Every request method also takes a `$timeoutSecs` (the last argument, except that `call()` of an Actor or a task takes `$log` after it) that overrides the tier for that call: seconds, a
tier name (`'short'`, `'medium'`, `'long'`), or `'noTimeout'`:

```php
Expand Down Expand Up @@ -120,8 +124,9 @@ $client = new ApifyClient(token: 'my-api-token', compression: new ZstdHttpCompre
```

Brotli and zstd need their PECL extensions, and gzip needs `zlib`. Choosing a codec without its extension throws
`RuntimeException` when the client is created. A custom algorithm is an
`Apify\Client\Http\HttpCompressorInterface` implementation: `contentEncoding(): string` and
`RuntimeException` when the client is created. `BrotliHttpCompressor::isAvailable()`,
`GzipHttpCompressor::isAvailable()`, and `ZstdHttpCompressor::isAvailable()` tell whether the codec can be used.
A custom algorithm is an `Apify\Client\Http\HttpCompressorInterface` implementation: `contentEncoding(): string` and
`compress(string $body): ?string`, which returns `null` to send the body as it is.

### Replaceable HTTP transport
Expand All @@ -137,8 +142,21 @@ $psr18 = new \GuzzleHttp\Client(['timeout' => 120]);
$client = new ApifyClient(token: 'my-api-token', httpClient: new Psr18HttpClient($psr18));
```

A transport implements two methods. Both take a prepared PSR-7 request and a per-attempt timeout in seconds, and
return a PSR-7 response. The client adds the token and the `User-Agent`, and retries failed requests.

| Method | Returns |
|---|---|
| `send(RequestInterface $request, float $timeoutSecs): ResponseInterface` | The response with its whole body. |
| `sendStreaming(RequestInterface $request, float $timeoutSecs): ResponseInterface` | The response with a live body stream, which the caller reads to the end. |

An error status is a normal response. Throw `TransportException` only when no response arrived (a refused
connection, DNS, a timeout, or a connection dropped before the body is complete).

`ActorClient::server()->request()` needs a transport that returns redirects as they are. It throws with
`Psr18HttpClient` and any transport that does not implement `NoRedirectHttpClientInterface`. See
`Psr18HttpClient` and any transport that does not implement `NoRedirectHttpClientInterface`, which adds
`sendWithoutRedirects(RequestInterface $request, float $timeoutSecs, bool $stream = false): ResponseInterface`. It
sends like `send()`, or like `sendStreaming()` with `$stream`, but returns a 3xx response instead of following it. See
[Server Actors](docs/actors.md).

## Error handling
Expand Down Expand Up @@ -194,8 +212,9 @@ A network failure or timeout is retried. When the retries run out, it throws
means the server answered with an error, and `TransportException` means no usable response arrived.

A success response whose body is not valid JSON, for an endpoint that returns JSON, is not retried and throws
`Apify\Client\Exception\InvalidResponseBodyException`. An error response with an unparsable body, such as an
HTML 502 page, throws the `ApifyApiException` subclass for its status with the raw body in the message.
`Apify\Client\Exception\InvalidResponseBodyException`, whose `getRawBody()` returns the body as received. An error
response with an unparsable body, such as an HTML 502 page, throws the `ApifyApiException` subclass for its status
with the raw body in the message.

`ApifyApiException` and `InvalidResponseBodyException` extend `Apify\Client\Exception\ApifyClientException`,
so one `catch` handles both:
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "apify/apify-client",
"description": "Official, experimental (AI-generated and AI-maintained) Apify API client for PHP: run Actors, manage storages (datasets, key-value stores, request queues), schedules, webhooks and more.",
"description": "Apify API client for PHP: run Actors, manage storages (datasets, key-value stores, request queues), schedules, webhooks and more.",
"type": "library",
"keywords": [
"apify",
Expand Down
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ the [resource pages](#resource-pages).
| `webhooks(): WebhookCollectionClient` | Webhook collection | List and create webhooks. |
| `webhookDispatch(string $id): WebhookDispatchClient` | Webhook dispatch client | Single webhook dispatch. |
| `webhookDispatches(): WebhookDispatchCollectionClient` | Webhook dispatch collection | List webhook dispatches. |
| `store(): StoreCollectionClient` | Store collection | Browse the public Apify Store. |
| `store(): StoreCollectionClient` | Store collection | Browse and search Apify Store. |
| `log(string $buildOrRunId): LogClient` | Log client | Log for a build or run, by ID. |
| `me(): UserClient` | User client | The authenticated user (`users/me`). |
| `user(string $id): UserClient` | User client | A public user profile, by ID. |
Expand Down
5 changes: 3 additions & 2 deletions docs/actors.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Addressed by ID or `username~name` (a `username/name` is accepted too).
- `update(mixed $newFields): Actor`
- `delete(): void`
- `start(mixed $input = null, ?ActorStartOptions $options = null): ActorRun`: start and return immediately.
- `call(mixed $input = null, ?ActorStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null): ActorRun`: start and wait. `$timeoutSecs` is the timeout of the start request and of every poll (default `'noTimeout'`).
- `call(mixed $input = null, ?ActorStartOptions $options = null, ?int $waitSecs = null, int|float|string|null $timeoutSecs = null, callable|false|null $log = null): ActorRun`: start and wait. `$timeoutSecs` is the timeout of the start request and of every poll (default `'noTimeout'`). `$log` is where the log of the run goes while the call waits: by default each message goes to the standard error stream, behind `{Actor name} runId:{run ID} -> `. Pass a callable that takes the message, or `false` for no redirection. A failure to redirect prints a warning and the call waits without it. See [`RunClient::redirectLog()`](runs.md).
- `validateInput(mixed $input = null, ?ValidateInputOptions $options = null): bool`

`$input` is a JSON-serializable array, or a `string` sent as it is. Set `$options->contentType` for a string, for
Expand Down Expand Up @@ -118,7 +118,8 @@ $response = $server->request('/search', new ActorServerRequestOptions(
- Single: `get(): ?ActorVersion`, `update(mixed $newFields): ActorVersion`, `delete(): void`.

The endpoint returns all versions in one response, so `list()` and `iterate()` take no options and `iterate()`
makes one request.
makes one request. `create()` and `update()` use the `long` timeout tier by default, since a version can carry its
source files.

```php
$version = $client->actor('me~my-actor')->versions()->create([
Expand Down
94 changes: 62 additions & 32 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
The snippets assume a `$client` and imported types (see [Namespaces](README.md#namespaces)). The first
[complete program](#a-complete-standalone-program) shows the scaffolding that the shorter snippets omit.

The programs on this page are in [`tests/Examples/`](../tests/Examples), and the `Test examples` CI step runs them
against the live API (`ExamplesTest`). Other snippets in the documentation are only checked with `php -l` by
`DocSnippetsTest`, which finds parse errors but not unknown classes or wrong types.
Each program on this page is the body of a class in [`tests/Examples/`](../tests/Examples), and the `Test examples`
CI step runs those classes against the live API (`ExamplesTest`). `ExampleDocsTest` checks that every snippet is
identical to the code that runs, and `ExamplesTest` also runs the standalone program. Other snippets in the
documentation are only checked with `php -l` by `DocSnippetsTest`, which finds parse errors but not unknown classes
or wrong types.

## A complete, standalone program

Expand All @@ -22,7 +24,11 @@ require 'vendor/autoload.php';
use Apify\Client\ApifyClient;
use Apify\Client\Exception\ApifyApiException;

$client = new ApifyClient(getenv('APIFY_TOKEN') ?: 'my-api-token');
// APIFY_API_URL is optional. It points the client at another API, such as a staging stack.
$client = new ApifyClient(
token: getenv('APIFY_TOKEN') ?: 'my-api-token',
baseUrl: getenv('APIFY_API_URL') ?: 'https://api.apify.com',
);

try {
// Run a Store Actor and wait up to 120 seconds for it to finish.
Expand All @@ -40,25 +46,43 @@ try {

```php
$run = $client->actor('apify/hello-world')->call(null, null, 120);
// getDefaultDatasetId() is ?string, so cast it to satisfy dataset(string $id).
$items = $client->dataset((string) $run->getDefaultDatasetId())->listItems();
$items = $client->dataset((string) $run->getDefaultDatasetId())->listItems(new DatasetListItemsOptions());
echo 'Item count: ' . $items->getCount() . PHP_EOL;
```

## Each storage: create, push, read

```php
$dataset = $client->datasets()->getOrCreate('example-ds');
$client->dataset($dataset->getId())->pushItems([['hello' => 'world']]);
$dsItems = $client->dataset($dataset->getId())->listItems();
// Dataset
$dataset = $client->datasets()->getOrCreate('php-example-ds-' . bin2hex(random_bytes(4)));
try {
$client->dataset((string) $dataset->getId())->pushItems([['hello' => 'world']]);
$items = $client->dataset((string) $dataset->getId())->listItems(new DatasetListItemsOptions());
echo 'Dataset items: ' . $items->getCount() . PHP_EOL;
} finally {
$client->dataset((string) $dataset->getId())->delete();
}

$store = $client->keyValueStores()->getOrCreate('example-kvs');
$client->keyValueStore($store->getId())->setRecordJson('OUTPUT', ['answer' => 42]);
$record = $client->keyValueStore($store->getId())->getRecord('OUTPUT');
// Key-value store
$store = $client->keyValueStores()->getOrCreate('php-example-kvs-' . bin2hex(random_bytes(4)));
try {
$client->keyValueStore((string) $store->getId())->setRecordJson('OUTPUT', ['answer' => 42]);
$record = $client->keyValueStore((string) $store->getId())->getRecord('OUTPUT');
echo 'KVS record: ' . ($record?->getValue() ?? '') . PHP_EOL;
} finally {
$client->keyValueStore((string) $store->getId())->delete();
}

$queue = $client->requestQueues()->getOrCreate('example-rq');
$client->requestQueue($queue->getId())->addRequest(new RequestQueueRequest('https://example.com', 'example'));
$head = $client->requestQueue($queue->getId())->listHead(10);
// Request queue
$queue = $client->requestQueues()->getOrCreate('php-example-rq-' . bin2hex(random_bytes(4)));
try {
$client->requestQueue((string) $queue->getId())
->addRequest(new RequestQueueRequest('https://example.com', 'example'));
$head = $client->requestQueue((string) $queue->getId())->listHead(10);
echo 'Queue head size: ' . count($head->getItems()) . PHP_EOL;
} finally {
$client->requestQueue((string) $queue->getId())->delete();
}
```

## Get own account details
Expand All @@ -74,7 +98,7 @@ if ($user !== null) {

```php
$created = $client->actors()->create([
'name' => 'my-example-actor',
'name' => 'php-example-actor-' . bin2hex(random_bytes(4)),
'isPublic' => false,
'versions' => [[
'versionNumber' => '0.0',
Expand All @@ -87,39 +111,44 @@ $created = $client->actors()->create([
]],
]);
try {
$build = $client->actor($created->getId())->build('0.0', new ActorBuildOptions());
$client->build($build->getId())->waitForFinish(300);
$run = $client->actor($created->getId())->call(null, null, 120);
$log = $client->run($run->getId())->log()->get();
$build = $client->actor((string) $created->getId())->build('0.0', new ActorBuildOptions());
$client->build((string) $build->getId())->waitForFinish(300);
$run = $client->actor((string) $created->getId())->call(null, null, 120);
$log = $client->run((string) $run->getId())->log()->get();
if ($log !== null) {
echo $log . PHP_EOL;
}
} finally {
$client->actor($created->getId())->delete();
$client->actor((string) $created->getId())->delete();
}
```

## Start a run, wait, then fetch the Actor's last run and its storages

```php
// Start the run, then wait for it to finish.
$started = $client->actor('apify/hello-world')->start();
$client->run($started->getId())->waitForFinish(120);
$client->run((string) $started->getId())->waitForFinish(120);

// Fetch the last run and read its storages via the run-nested convenience accessors.
// Fetch the Actor's last successful run and read its storages through the run-nested
// convenience accessors, which resolve the last run's dataset, key-value store and
// request queue without needing their individual IDs.
$lastRun = $client->actor('apify/hello-world')->lastRun(new LastRunOptions(status: 'SUCCEEDED'));
$last = $lastRun->get();
if ($last !== null) {
$lastRun->dataset()->listItems();
$lastRun->dataset()->listItems(new DatasetListItemsOptions());
$lastRun->keyValueStore()->getRecord('OUTPUT');
$lastRun->requestQueue()->listHead(10);
echo 'Last run: ' . $last->getId() . PHP_EOL;
}
```

## Lazy iteration of Store Actors

```php
$shown = 0;
// The second argument is the per-page (chunk) size; StoreListOptions::limit would cap the total.
// The second argument is the per-page (chunk) size; the iterator fetches pages lazily as we
// consume items. StoreListOptions::limit (unset here) would cap the total across all pages.
foreach ($client->store()->iterate(new StoreListOptions(), 10) as $item) {
echo $item->getName() . PHP_EOL;
if (++$shown >= 5) {
Expand All @@ -131,11 +160,12 @@ foreach ($client->store()->iterate(new StoreListOptions(), 10) as $item) {
## Run an Actor with log redirection

```php
// Start the run without waiting, then redirect its log to stdout live. The streaming endpoint keeps
// the connection open and emits log lines in real time; reading to EOF also waits for the run to end.
$run = $client->actor('apify/hello-world')->start();
$stream = $client->run($run->getId())->getStreamedLog();
while (!$stream->eof()) {
echo $stream->read(8192);
}
// call() redirects the log of the run while it waits. Without the `log` argument, the messages go to the
// standard error stream, behind "{Actor name} runId:{run ID} -> ". A callable receives each message
// instead, and `false` turns the redirection off.
$run = $client->actor('apify/hello-world')->call(null, null, 120, log: static function (string $message): void {
echo 'Actor log: ' . $message . PHP_EOL;
});

echo 'Run status: ' . $run->getStatus() . PHP_EOL;
```
Loading
Loading