> ## 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-Client-Bibliothek

> Installieren, initialisieren, Methoden auf Endpoints abbilden und Fehler mit dem offiziellen Python-SDK octoparse-client behandeln.

`octoparse-client` ist der offizielle Python-Client für Data Hub. Er wrappt nur die öffentliche `/v1`-REST-API und hängt allein von `httpx` ab. Methoden mapen 1:1 auf Endpoints, Parameternamen entsprechen REST, Rückgaben sind der rohe `data`-Payload (`dict` / `list`). Aktuelle Version 0.2.9, Python 3.10+.

## Installation

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

## Initialisierung

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

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

| Parameter  | Beschreibung                                                                                                                                                         |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `api_key`  | Data Hub API-Schlüssel. Ohne Angabe wird `OCTOPARSE_API_KEY` gelesen. Fehlt er weiterhin, ist der Client anonym und kann nur anonyme Endpoints aufrufen.             |
| `base_url` | Service-URL. Ohne Angabe wird `OCTOPARSE_BASE_URL` gelesen, Standard ist `https://api-datahub.octoparse.com`. Für lokale oder Staging-Umgebungen explizit übergeben. |
| `timeout`  | HTTP-Timeout pro Request in Sekunden. Standard 90.                                                                                                                   |

`Client` unterstützt `with` und schließt Verbindungen beim Exit. Auch `client.close()` möglich. Das SDK lädt keine `.env`-Dateien; bei Bedarf selbst laden.

## Methoden-zu-Endpoint-Zuordnung

| Methode                                                                | Endpoint                                  | Hinweise                                          |
| ---------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------- |
| `meta()`                                                               | `GET /v1/meta`                            | Plattform-Konstanten                              |
| `search(q, *, limit, offset, ...)`                                     | `GET /v1/data-apps`                       | Eine Seite Karten, inkl. `pagination`             |
| `get_app(app_id)`                                                      | `GET /v1/data-apps/{app_id}`              | Vollständiges App-Detail                          |
| `run(app_id, inputs, *, wait, max_records, version, build)`            | `POST /v1/data-apps/{app_id}/runs`        | Run starten                                       |
| `call(app_id, inputs, *, max_records, timeout, raise_on_failure, ...)` | `POST` + Poll                             | Blocking-Helper: warten bis terminal oder Timeout |
| `get_run(run_id, *, wait)`                                             | `GET /v1/runs/{run_id}`                   | Status- und Abrechnungs-Snapshot                  |
| `list_runs_page(filters)`                                              | `GET /v1/runs`                            | Eine Seite Runs, inkl. `pagination`               |
| `list_runs(filters)`                                                   | `GET /v1/runs`                            | Eine Seite Runs, nur Items                        |
| `iterate_runs(filters)`                                                | `GET /v1/runs`                            | Iterator, der automatisch paginiert               |
| `cancel(run_id)`                                                       | `POST /v1/runs/{run_id}/cancel`           | Run abbrechen                                     |
| `get_records(run_id, *, offset, limit, fields)`                        | `GET /v1/runs/{run_id}/records`           | Eine Seite Ergebnisdatensätze                     |
| `iterate_records(run_id, *, batch, fields)`                            | `GET /v1/runs/{run_id}/records`           | Iterator, der automatisch paginiert               |
| `export_records(run_id, format)`                                       | `GET /v1/runs/{run_id}/records`           | Voller Export als `jsonl`/`csv`-Text              |
| `list_datasets(*, offset, limit)`                                      | `GET /v1/datasets`                        | Dataset-Liste                                     |
| `set_dataset_retention(dataset_id, retained)`                          | `PUT /v1/datasets/{dataset_id}/retention` | Retention-Flag setzen                             |
| `get_dataset_records(dataset_id, *, offset, limit, fields)`            | `GET /v1/datasets/{dataset_id}/records`   | Eine Seite Dataset-Datensätze                     |
| `iterate_dataset_records(dataset_id, *, batch, fields)`                | `GET /v1/datasets/{dataset_id}/records`   | Iterator, der automatisch paginiert               |
| `account()`                                                            | `GET /v1/account`                         | Kontoinfo und kumulierter Spend                   |
| `billing(*, group_by, created_from, created_to, tz_offset)`            | `GET /v1/billing`                         | Abrechnungsaggregation                            |

Die `filters` der Run-Liste unterstützen `status`, `data_app`, `triggered_by`, `run_kind`, `credential`, `created_from`, `created_to` sowie `offset` / `limit`. Publishing-, Betriebs- und Secrets-Endpoints sind nicht gekapselt; rufen Sie REST direkt auf.

## Typische Verwendung

```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)
```

## Fehlerbehandlung

API-Fehlerantworten lösen `ApiError` aus. Die Felder entsprechen dem REST-`error`-Objekt:

| Attribut      | Bedeutung                                                                    |
| ------------- | ---------------------------------------------------------------------------- |
| `status_code` | HTTP-Status                                                                  |
| `code`        | Stabile Fehler-ID für Verzweigungen                                          |
| `category`    | Grobe Fehlerklasse                                                           |
| `message`     | Englische Beschreibung                                                       |
| `retryable`   | Ob dieselbe Anfrage erneut versucht werden kann                              |
| `details`     | Probleme auf Feldebene bei fehlgeschlagener Eingabevalidierung, sonst `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
```

`RunFailed` wird ausgelöst, wenn `call(..., raise_on_failure=True)` mit `FAILED` / `CANCELLED` / `EXPIRED` endet. Das Attribut `run` enthält das vollständige Run-Objekt.

## App-Referenzen

`get_app()`, `run()`, `call()` und der Run-List-Filter `data_app` akzeptieren beide Formen: zweisegmentig `<namespace>/<app_name>` (menschenlesbar, bricht nach Rename) und stabiles `app_id` (`app_<hex>`, überlebt Rename). Für langlebige Integrationen `app_id` speichern.
