Skip to content

Latest commit

 

History

History
171 lines (142 loc) · 6.35 KB

examples.md

File metadata and controls

171 lines (142 loc) · 6.35 KB

Runnable examples

The snippets assume a $client and imported types (see Namespaces). The first complete program shows the scaffolding that the shorter snippets omit.

Each program on this page is the body of a class in 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

Save this program as example.php and run it with php example.php after composer require apify/apify-client. It has the <?php tag, the Composer autoloader, and the use imports that the shorter snippets leave out.

<?php

declare(strict_types=1);

require 'vendor/autoload.php';

use Apify\Client\ApifyClient;
use Apify\Client\Exception\ApifyApiException;

// 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.
    $run = $client->actor('apify/hello-world')->call(null, null, 120);

    // getDefaultDatasetId() is ?string, so cast it for dataset(string $id).
    $items = $client->dataset((string) $run->getDefaultDatasetId())->listItems();
    echo 'Item count: ' . $items->getCount() . PHP_EOL;
} catch (ApifyApiException $e) {
    echo 'API error ' . $e->getStatusCode() . ': ' . $e->getApiMessage() . PHP_EOL;
}

Run a store Actor and read its default dataset

$run = $client->actor('apify/hello-world')->call(null, null, 120);
$items = $client->dataset((string) $run->getDefaultDatasetId())->listItems(new DatasetListItemsOptions());
echo 'Item count: ' . $items->getCount() . PHP_EOL;

Each storage: create, push, read

// 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();
}

// 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();
}

// 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

$user = $client->me()->get();
if ($user !== null) {
    echo 'Account ' . $user->getId() . ' / ' . $user->getUsername() . PHP_EOL;
}

Create a new Actor, build it, run it, wait, and print the finished run log

$created = $client->actors()->create([
    'name' => 'php-example-actor-' . bin2hex(random_bytes(4)),
    'isPublic' => false,
    'versions' => [[
        'versionNumber' => '0.0',
        'sourceType' => 'SOURCE_FILES',
        'buildTag' => 'latest',
        'sourceFiles' => [
            ['name' => 'Dockerfile', 'format' => 'TEXT', 'content' => "FROM apify/actor-node:20\nCOPY . ./\nCMD node main.js"],
            ['name' => 'main.js', 'format' => 'TEXT', 'content' => "console.log('hi');"],
        ],
    ]],
]);
try {
    $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((string) $created->getId())->delete();
}

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

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

// 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(new DatasetListItemsOptions());
    $lastRun->keyValueStore()->getRecord('OUTPUT');
    $lastRun->requestQueue()->listHead(10);
    echo 'Last run: ' . $last->getId() . PHP_EOL;
}

Lazy iteration of Store Actors

$shown = 0;
// 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) {
        break;
    }
}

Run an Actor with log redirection

// 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;