> ## Documentation Index
> Fetch the complete documentation index at: https://www.octoparse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Python クライアントライブラリ

> 公式 Python SDK octoparse-client。

`octoparse-client` は Data Hub 公式 Python クライアント。公開 `/v1` REST のみラップし依存は `httpx` のみ。メソッドはエンドポイントと 1 対 1、パラメータ名は REST と同じ、戻り値は応答 `data`。

## インストール

```bash theme={null}
pip install octoparse-client
```

## 初期化

```python theme={null}
from octoparse_client import Client

client = Client(api_key="<your API key>")
```

| Parameter  | Description                                                                                |
| ---------- | ------------------------------------------------------------------------------------------ |
| `api_key`  | Data Hub API キー。省略時は `OCTOPARSE_API_KEY`。それでも無ければ匿名で匿名エンドポイントのみ。                           |
| `base_url` | サービス URL。省略時は `OCTOPARSE_BASE_URL`、既定 `https://api-datahub.octoparse.com`。ローカル／ステージングでは明示。 |
| `timeout`  | リクエストあたり HTTP タイムアウト（秒）。既定 90。                                                             |

`Client` は `with` 対応で終了時に接続を閉じます。`client.close()` も可。SDK は `.env` を読みません。必要なら自分で。

## メソッドとエンドポイントの対応

| Method                                                                 | Endpoint                                  | Notes                                           |
| ---------------------------------------------------------------------- | ----------------------------------------- | ----------------------------------------------- |
| `meta()`                                                               | `GET /v1/meta`                            | Platform constants                              |
| `search(q, *, limit, offset, ...)`                                     | `GET /v1/data-apps`                       | One page of cards, including `pagination`       |
| `get_app(app_id)`                                                      | `GET /v1/data-apps/{app_id}`              | Full app detail                                 |
| `run(app_id, inputs, *, wait, max_records, version, build)`            | `POST /v1/data-apps/{app_id}/runs`        | Start a run                                     |
| `call(app_id, inputs, *, max_records, timeout, raise_on_failure, ...)` | `POST` + poll                             | Blocking helper: wait until terminal or timeout |
| `get_run(run_id, *, wait)`                                             | `GET /v1/runs/{run_id}`                   | 状態と課金スナップショット                                   |
| `list_runs_page(filters)`                                              | `GET /v1/runs`                            | One page of runs, including `pagination`        |
| `list_runs(filters)`                                                   | `GET /v1/runs`                            | 実行 1 ページ（items のみ）                              |
| `iterate_runs(filters)`                                                | `GET /v1/runs`                            | 自動ページングイテレータ                                    |
| `cancel(run_id)`                                                       | `POST /v1/runs/{run_id}/cancel`           | Cancel a run                                    |
| `get_records(run_id, *, offset, limit, fields)`                        | `GET /v1/runs/{run_id}/records`           | One page of result records                      |
| `iterate_records(run_id, *, batch, fields)`                            | `GET /v1/runs/{run_id}/records`           | 自動ページングイテレータ                                    |
| `export_records(run_id, format)`                                       | `GET /v1/runs/{run_id}/records`           | Full export as `jsonl` / `csv` text             |
| `list_datasets(*, offset, limit)`                                      | `GET /v1/datasets`                        | データセット一覧                                        |
| `set_dataset_retention(dataset_id, retained)`                          | `PUT /v1/datasets/{dataset_id}/retention` | Set retention flag                              |
| `get_dataset_records(dataset_id, *, offset, limit, fields)`            | `GET /v1/datasets/{dataset_id}/records`   | One page of dataset records                     |
| `iterate_dataset_records(dataset_id, *, batch, fields)`                | `GET /v1/datasets/{dataset_id}/records`   | 自動ページングイテレータ                                    |
| `account()`                                                            | `GET /v1/account`                         | アカウント情報と累計支出                                    |
| `billing(*, group_by, created_from, created_to, tz_offset)`            | `GET /v1/billing`                         | Billing aggregation                             |

実行一覧 `filters` は `status`、`data_app`、`triggered_by`、`run_kind`、`credential`、`created_from`、`created_to` と `offset`/`limit`。公開・運用・シークレット系は未ラップ — REST 直接。

## 典型的な使い方

```python theme={null}
from octoparse_client import Client, ApiError, RunFailed

with Client(api_key="<your API key>") as client:
    # Discover
    page = client.search("reviews", limit=5)
    for card in page["items"]:
        print(card["app_id"], card["namespace"], card["app_name"])
    detail = client.get_app("carol/reviews-query")

    # Run and consume. Timeouts are seconds. TimeoutError does not cancel the server-side run.
    run = client.call(
        "carol/reviews-query",
        {"product": "p-9001"},
        max_records=100,
        timeout=120,
        raise_on_failure=True,
    )
    for record in client.iterate_records(run["run_id"]):
        print(record)

    # Non-blocking: start, then poll yourself
    started = client.run("carol/reviews-query", {"product": "p-9002"}, wait=0)
    polled = client.get_run(started["run_id"], wait=60)

    # Reconcile spend
    print(client.billing(group_by="data_app", tz_offset=480))
    for r in client.iterate_runs(created_from="2026-09-01T00:00:00+08:00"):
        print(r["run_id"], r["status"], r["billing"]["total"])

    # Results are kept 90 days by default; mark datasets you need longer
    client.set_dataset_retention(run["dataset_id"], True)
```

## エラー処理

API エラーは `ApiError` を送出。フィールドは REST `error` と同じ:

| Attribute     | Meaning                                                          |
| ------------- | ---------------------------------------------------------------- |
| `status_code` | HTTP status                                                      |
| `code`        | 分岐用の安定エラー id                                                     |
| `category`    | Broad class                                                      |
| `message`     | English description                                              |
| `retryable`   | 同一リクエストを再試行できるか                                                  |
| `details`     | Field-level issues on input validation failure, otherwise `None` |

```python theme={null}
from octoparse_client import ApiError

try:
    client.run("carol/reviews-query", {})
except ApiError as e:
    if e.code == "invalid-input":
        for d in e.details or []:
            print(d["path"], d["message"])
    elif e.retryable:
        # back off and retry
        ...
    else:
        raise
```

`call(..., raise_on_failure=True)` が `FAILED` / `CANCELLED` / `EXPIRED` で終わると `RunFailed`。`run` 属性に実行オブジェクト全文。

## App 参照

`get_app()`、`run()`、`call()`、実行一覧の `data_app` フィルタは両形式を受付: 2 段 `<namespace>/<app_name>`（人が読める、改名で壊れる）と安定 `app_id`（`app_<hex>`、改名耐性）。長期連携は `app_id` 推奨。
