mcpField
A
apify-sdk-integration

apify-sdk-integration

github.com/apify開発2.5k3.2k 回インストール1 週間前に更新
リポジトリ

apify-sdk-integration について

JavaScript、TypeScript、Pythonのapify-client、または他言語向けREST APIで、アプリにApify Actorの実行機能を組み込む開発スキルです。実行制御、結果取得、統合方法を扱います。

主な機能

  1. 01apify-clientによるActor実行
  2. 02同期・非同期実行への対応
  3. 03データセットとキーバリューストアの取得
  4. 04他言語からのREST API呼び出し
  5. 05実行状態とエラーの処理

活用シーン

  1. 01アプリへのウェブスクレイピング追加
  2. 02Actorの出力をデータパイプラインに接続
  3. 03Apifyをアプリのバックエンドとして統合

MCP 対応

search-actorsやfetch-actor-detailsなどのApify MCPツールを使い、Actorの検索や入力スキーマ・出力・料金の確認を推奨します。

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/apify/agent-skills --skill apify-sdk-integration

インストール後、Claude Code で/apify-sdk-integrationを入力して読み込まれたか確認します。

詳細

Apify SDK の統合

既存のアプリケーションに Apify Actor の実行機能を追加します。このスキルでは、JS/TS および Python 向けの apify-client パッケージと、その他の言語向けの REST API を扱います。

このスキルを使用するタイミング

  • 既存のアプリにウェブスクレイピングや自動化を追加する場合
  • アプリケーションコードから Apify Actor をプログラムで呼び出す場合
  • Apify をバックエンドサービスとして利用する製品を構築する場合
  • Actor の結果をデータパイプラインに統合する場合

重要:パッケージ名

apify-client は、アプリから Actor を呼び出すための API クライアントです。 apify は Actor を構築するための SDK です(この用途では誤ったパッケージです)。

必ず apify-client をインストールしてください。統合には apify をインストールしないでください。

前提条件

ユーザーには APIFY_TOKEN が必要です。作成するには https://console.apify.com/settings/integrations の Console > Settings > Integrations を案内してください。アカウントを持っていない場合は、https://console.apify.com/sign-up から登録できます(無料、クレジットカード不要)。

トークンは安全に保管してください。環境変数またはシークレットマネージャーを使用し、コードに直接記述しないでください。

適切な Actor を見つける

統合コードを書く前に、ユーザーのニーズに合った Actor を見つけてください。利用可能な場合は MCP ツールを使用します。

  • search-actors — キーワードで Apify Store を検索します
  • fetch-actor-details — Actor の入力スキーマ、出力形式、料金を取得します

または、https://apify.com/store を参照してください。Actor の Store URL の末尾に .md を付けると、ドキュメントを Markdown 形式で取得できます。

JavaScript / TypeScript

インストール
npm install apify-client
同期実行(結果を待機)
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });

const run = await client.actor('apify/web-scraper').call({
    startUrls: [{ url: 'https://example.com' }],
    maxPagesPerCrawl: 10,
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();

.call() は Actor が終了するまで処理をブロックします。実行時間が短い(数分以内の)Actor に使用してください。

非同期実行(開始後、後でポーリング/取得)
const run = await client.actor('apify/web-scraper').start({
    startUrls: [{ url: 'https://example.com' }],
});

// Poll for completion
const finishedRun = await client.run(run.id).waitForFinish();

// Retrieve results
const { items } = await client.dataset(finishedRun.defaultDatasetId).listItems();

実行時間の長い Actor や、すぐに実行 ID が必要な場合は、.start() と .waitForFinish() を使用してください。

結果の取得
// Dataset items (structured data from pushData)
const { items } = await client.dataset(run.defaultDatasetId).listItems({
    limit: 100,
    offset: 0,
});

// Key-value store (files, screenshots, etc.)
const record = await client.keyValueStore(run.defaultKeyValueStoreId).getRecord('OUTPUT');
エラー処理
try {
    const run = await client.actor('apify/web-scraper').call(input);

    if (run.status !== 'SUCCEEDED') {
        const log = await client.log(run.id).get();
        throw new Error(`Actor failed with status ${run.status}: ${log}`);
    }

    const { items } = await client.dataset(run.defaultDatasetId).listItems();
} catch (error) {
    if (error.message?.includes('not found')) {
        // Actor ID is wrong or Actor was deleted
    } else if (error.statusCode === 401) {
        // Invalid or missing APIFY_TOKEN
    }
    throw error;
}

Python

インストール
pip install apify-client
同期実行
from apify_client import ApifyClient
import os

client = ApifyClient(token=os.environ['APIFY_TOKEN'])

run = client.actor('apify/web-scraper').call(run_input={
    'startUrls': [{'url': 'https://example.com'}],
    'maxPagesPerCrawl': 10,
})

items = client.dataset(run['defaultDatasetId']).list_items().items
非同期実行
run = client.actor('apify/web-scraper').start(run_input={
    'startUrls': [{'url': 'https://example.com'}],
})

# Poll for completion
finished_run = client.run(run['id']).wait_for_finish()

items = client.dataset(finished_run['defaultDatasetId']).list_items().items
非同期クライアント(asyncio)
from apify_client import ApifyClientAsync

client = ApifyClientAsync(token=os.environ['APIFY_TOKEN'])

run = await client.actor('apify/web-scraper').call(run_input={
    'startUrls': [{'url': 'https://example.com'}],
})

items = (await client.dataset(run['defaultDatasetId']).list_items()).items

REST API(任意の言語)

公式クライアントがない言語では、REST API を直接使用してください。

実行の開始
POST https://api.apify.com/v2/actors/{actorId}/runs
Authorization: Bearer <APIFY_TOKEN>
Content-Type: application/json

{ "startUrls": [{ "url": "https://example.com" }] }
実行ステータスの取得
GET https://api.apify.com/v2/actor-runs/{runId}
Authorization: Bearer <APIFY_TOKEN>
データセット項目の取得
GET https://api.apify.com/v2/datasets/{datasetId}/items?format=json
Authorization: Bearer <APIFY_TOKEN>

API リファレンス全文:https://docs.apify.com/api/v2

ベストプラクティス

  • タイムアウトを設定する: 無期限の待機を避けるため、Actor の入力で timeoutSecs を渡すか、.call() で waitSecs を使用してください。
  • 大規模なデータセットをページネーションする: データセット項目の取得時に limit と offset を使用してください。デフォルトの上限は 25 万件です。
  • クライアントを再利用する: ApifyClient のインスタンスを 1 つ作成し、呼び出し間で再利用してください。
  • Actor 固有の入力を処理する: Actor ごとに独自の入力スキーマがあります。入力を組み立てる前に、fetch-actor-details MCP ツールを使用するか、Actor の Store URL の末尾に .md を付けてスキーマを取得してください。

ドキュメント

Apify MCP サーバーを利用できる場合は、開発中の文脈に応じたドキュメント検索に search-apify-docs および fetch-apify-docs ツールを使用してください。

コメント