---
title: "Call the hosted API from Python"
description: "Query hosted analytics rows and Reports with httpx, handle retries, and generate typed Python models from OpenAPI."
canonical_url: "https://gscdump.com/gscdump-sdk/guides/build-integrations/python"
---

> Index of every page on this site: [llms.txt](https://gscdump.com/llms.txt)

# Call the hosted API from Python

Query hosted analytics from a Python service with `httpx` and a server-held Bearer API key. Generate typed models or a client from the v1 OpenAPI documents.

::pre{tabindex="0" svg="<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 579.345 181.8\" width=\"579.345\" height=\"181.8\" style=\"--bg:var(--ui-bg-muted);--fg:var(--ui-text-highlighted);--accent:var(--ui-link)\">
<style>
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&amp;display=swap');
  text { font-family: 'Inter', system-ui, sans-serif; }
  svg {
    /* Derived from --bg and --fg (overridable via --line, --accent, etc.) */
    --_text:          var(--fg);
    --_text-sec:      var(--muted, color-mix(in srgb, var(--fg) 60%, var(--bg)));
    --_text-muted:    var(--muted, color-mix(in srgb, var(--fg) 40%, var(--bg)));
    --_text-faint:    color-mix(in srgb, var(--fg) 25%, var(--bg));
    --_line:          var(--line, color-mix(in srgb, var(--fg) 50%, var(--bg)));
    --_arrow:         var(--accent, color-mix(in srgb, var(--fg) 85%, var(--bg)));
    --_node-fill:     var(--surface, color-mix(in srgb, var(--fg) 3%, var(--bg)));
    --_node-stroke:   var(--border, color-mix(in srgb, var(--fg) 20%, var(--bg)));
    --_group-fill:    var(--bg);
    --_group-hdr:     color-mix(in srgb, var(--fg) 5%, var(--bg));
    --_inner-stroke:  color-mix(in srgb, var(--fg) 12%, var(--bg));
    --_key-badge:     color-mix(in srgb, var(--fg) 10%, var(--bg));
  }
</style>
<defs>
  <marker id=\"arrowhead\" markerWidth=\"8\" markerHeight=\"5\" refX=\"7\" refY=\"2.5\" orient=\"auto\">
    <polygon points=\"0 0, 8 2.5, 0 5\" fill=\"var(--_arrow)\" stroke=\"var(--_arrow)\" stroke-width=\"0.75\" stroke-linejoin=\"round\" />
  </marker>
  <marker id=\"arrowhead-start\" markerWidth=\"8\" markerHeight=\"5\" refX=\"1\" refY=\"2.5\" orient=\"auto-start-reverse\">
    <polygon points=\"8 0, 0 2.5, 8 5\" fill=\"var(--_arrow)\" stroke=\"var(--_arrow)\" stroke-width=\"0.75\" stroke-linejoin=\"round\" />
  </marker>
</defs>
<polyline class=\"edge\" data-from=\"Service\" data-to=\"Hosted\" data-style=\"solid\" data-arrow-start=\"false\" data-arrow-end=\"true\" data-label=\"Authorization: Bearer\" points=\"171.61100000000005,58.45 378.83500000000004,58.45\" fill=\"none\" stroke=\"var(--_line)\" stroke-width=\"1\" marker-end=\"url(#arrowhead)\" />
<polyline class=\"edge\" data-from=\"OpenAPI\" data-to=\"Models\" data-style=\"solid\" data-arrow-start=\"false\" data-arrow-end=\"true\" points=\"184.20799999999997,123.35000000000001 232.20799999999997,123.35000000000001\" fill=\"none\" stroke=\"var(--_line)\" stroke-width=\"1\" marker-end=\"url(#arrowhead)\" />
<g class=\"edge-label\" data-from=\"Service\" data-to=\"Hosted\" data-label=\"Authorization: Bearer\">
  <rect x=\"215.61100000000005\" y=\"42.45\" width=\"119.22400000000002\" height=\"30.3\" rx=\"2\" ry=\"2\" fill=\"var(--bg)\" stroke=\"var(--_inner-stroke)\" stroke-width=\"1\" />
  <text x=\"275.22300000000007\" y=\"57.6\" text-anchor=\"middle\" font-size=\"11\" font-weight=\"400\" fill=\"var(--_text-sec)\" dy=\"3.8499999999999996\">Authorization: Bearer</text>
</g>
<g class=\"node\" data-id=\"Service\" data-label=\"Python service\" data-shape=\"rectangle\">
  <rect x=\"40.00000000000006\" y=\"40\" width=\"131.611\" height=\"36.900000000000006\" rx=\"0\" ry=\"0\" fill=\"var(--_node-fill)\" stroke=\"var(--_node-stroke)\" stroke-width=\"0.75\" />
  <text x=\"105.80550000000005\" y=\"58.45\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"500\" fill=\"var(--_text)\" dy=\"4.55\">Python service</text>
</g>
<g class=\"node\" data-id=\"Hosted\" data-label=\"gscdump hosted API\" data-shape=\"rectangle\">
  <rect x=\"378.83500000000004\" y=\"40\" width=\"160.51\" height=\"36.900000000000006\" rx=\"0\" ry=\"0\" fill=\"var(--_node-fill)\" stroke=\"var(--_node-stroke)\" stroke-width=\"0.75\" />
  <text x=\"459.09000000000003\" y=\"58.45\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"500\" fill=\"var(--_text)\" dy=\"4.55\">gscdump hosted API</text>
</g>
<g class=\"node\" data-id=\"OpenAPI\" data-label=\"v1 OpenAPI JSON\" data-shape=\"rectangle\">
  <rect x=\"40\" y=\"104.9\" width=\"144.20799999999997\" height=\"36.900000000000006\" rx=\"0\" ry=\"0\" fill=\"var(--_node-fill)\" stroke=\"var(--_node-stroke)\" stroke-width=\"0.75\" />
  <text x=\"112.10399999999998\" y=\"123.35000000000001\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"500\" fill=\"var(--_text)\" dy=\"4.55\">v1 OpenAPI JSON</text>
</g>
<g class=\"node\" data-id=\"Models\" data-label=\"Typed Python models\" data-shape=\"rectangle\">
  <rect x=\"232.20799999999997\" y=\"104.9\" width=\"167.92\" height=\"36.900000000000006\" rx=\"0\" ry=\"0\" fill=\"var(--_node-fill)\" stroke=\"var(--_node-stroke)\" stroke-width=\"0.75\" />
  <text x=\"316.16799999999995\" y=\"123.35000000000001\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"500\" fill=\"var(--_text)\" dy=\"4.55\">Typed Python models</text>
</g>
</svg>"}
```mermaid
flowchart LR
  Service[Python service] -->|Authorization: Bearer| Hosted[gscdump hosted API]
  OpenAPI[v1 OpenAPI JSON] --> Models[Typed Python models]
```
::

## Before you start

Complete [Hosted first result](https://gscdump.com/gscdump-sdk/guides/start/hosted-first-result) to create a user API key and copy your Site ID (`s_...`). Install `httpx` in your Python environment (`pip install httpx` or `uv add httpx`). Set `GSCDUMP_API_KEY` and `GSCDUMP_SITE_ID` in the server environment.

Hosted v1 requires `Authorization: Bearer <GSCDUMP_API_KEY>`. Do not send `X-API-Key` on v1 endpoints.

## Query rows and Reports with httpx

Use one shared `httpx.Client` for requests to `https://gscdump.com`. Both `POST /api/analytics/v1/sites/{siteId}/rows` and `POST /api/analytics/v1/sites/{siteId}/reports` are idempotent queries, so bounded retries are safe when an error envelope reports `retryable: true`.

::pre{tabindex="0"}
```python
from __future__ import annotations

import email.utils
import os
import time
from typing import Any

import httpx

BASE_URL = "https://gscdump.com"
EXPECTED_API_VERSION = "1.0"
MAX_ATTEMPTS = 3


class GscdumpApiError(RuntimeError):
    def __init__(
        self,
        *,
        status_code: int,
        code: str,
        message: str,
        request_id: str | None,
        retryable: bool,
        details: dict[str, Any],
    ) -> None:
        super().__init__(f"{code} (status={status_code}, request_id={request_id}): {message}")
        self.status_code = status_code
        self.code = code
        self.request_id = request_id
        self.retryable = retryable
        self.details = details


def parse_retry_after(header_value: str | None) -> float | None:
    if not header_value:
        return None
    try:
        return max(0.0, float(header_value))
    except ValueError:
        pass
    try:
        target = email.utils.parsedate_to_datetime(header_value)
    except (TypeError, ValueError):
        return None
    return max(0.0, target.timestamp() - time.time())


def post_idempotent(
    client: httpx.Client,
    path: str,
    payload: dict[str, Any],
) -> dict[str, Any]:
    for attempt in range(1, MAX_ATTEMPTS + 1):
        response = client.post(path, json=payload)
        api_version = response.headers.get("GSCdump-API-Version")
        if api_version and api_version != EXPECTED_API_VERSION:
            raise RuntimeError(f"Unexpected GSCdump-API-Version: {api_version}")

        if response.is_success:
            return response.json()

        try:
            body = response.json() if response.content else {}
        except ValueError:
            body = {}

        err = body.get("error") if isinstance(body, dict) else None
        if not isinstance(err, dict):
            if response.status_code in (429, 503) and attempt < MAX_ATTEMPTS:
                retry_after = parse_retry_after(response.headers.get("Retry-After"))
                backoff = min(2.0, 0.25 * (2 ** (attempt - 1)))
                time.sleep(max(backoff, retry_after or 0.0))
                continue
            response.raise_for_status()

        api_error = GscdumpApiError(
            status_code=response.status_code,
            code=str(err.get("code", "unknown_error")),
            message=str(err.get("message", "Request failed")),
            request_id=err.get("requestId") or response.headers.get("x-request-id"),
            retryable=bool(err.get("retryable", False)),
            details=err.get("details") if isinstance(err.get("details"), dict) else {},
        )

        if api_error.retryable and attempt < MAX_ATTEMPTS:
            retry_after = parse_retry_after(response.headers.get("Retry-After"))
            backoff = min(2.0, 0.25 * (2 ** (attempt - 1)))
            time.sleep(max(backoff, retry_after or 0.0))
            continue

        raise api_error

    raise RuntimeError("Retry budget exhausted")


api_key = os.environ["GSCDUMP_API_KEY"]
site_id = os.environ["GSCDUMP_SITE_ID"]

with httpx.Client(
    base_url=BASE_URL,
    headers={
        "Authorization": f"Bearer {api_key}",
        "Accept": "application/json",
    },
    timeout=30.0,
) as client:
    rows_response = post_idempotent(
        client,
        f"/api/analytics/v1/sites/{site_id}/rows",
        {
            "dimensions": ["query"],
            "metrics": ["clicks", "impressions"],
            "searchType": "web",
            "rowLimit": 100,
        },
    )
    print(rows_response["data"]["rows"], rows_response["meta"]["requestId"])

    report_response = post_idempotent(
        client,
        f"/api/analytics/v1/sites/{site_id}/reports",
        {
            "state": {
                "dimensions": ["query"],
                "searchType": "web",
            },
        },
    )
    report = report_response["data"]
    print(report["totals"], report["meta"]["syncStatus"], report["meta"]["newestDateSynced"])
```
::

Every successful v1 response returns `{ "data": ..., "meta": ... }` and sends `GSCdump-API-Version: 1.0`, `x-request-id`, `Cache-Control: private, no-store`, and `Vary: Authorization`. List Reports reject the `date` dimension. When you need daily series, call `POST /api/analytics/v1/sites/{siteId}/reports/detail`.

## Handle errors and rate limits

Every v1 failure returns `{ "error": { "code", "message", "requestId", "retryable", "details" } }`. Branch on `error.code` and `error.retryable`, and log `error.requestId` without logging `Authorization`.

::table{tabindex="0"}
| Status                       | Meaning                                                                                    | Action                                                               |
| ---------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- |
| `429 rate_limited`           | Rate limit reached for this credential and operation                                       | Wait for `Retry-After` before retrying                               |
| `503` with `retryable: true` | Limiter or upstream temporarily unavailable (`Retry-After: 5` on limiter fail-closed)      | Wait for `Retry-After` and retry idempotent operations               |
| `401` or `403`               | Invalid key, missing scope, or unauthorized Site                                           | Fix credentials or Site access; do not retry                         |
| `409 invalid_request`        | Domain refusal, such as `record_not_ready` or `range_not_synced` in `error.details.reason` | Inspect `error.details`; an immediate retry returns the same refusal |
::

Only retry operations whose OpenAPI `x-gscdump-semantics.retry` value is `"idempotent"`. Do not automatically retry mutations marked `retry: "never"`. See [Errors and retry](https://gscdump.com/gscdump-sdk/guides/operate/errors-and-retry) and the [hosted HTTP reference](https://gscdump.com/gscdump-sdk/api/hosted-http#idempotency-and-retries) for the exact mutation list.

## Generate typed Python models or a client

The hosted API publishes OpenAPI 3.1 documents for each HTTP surface:

- Analytics surface: `https://gscdump.com/openapi/analytics.v1.json`
- Partner surface: `https://gscdump.com/openapi/partner.v1.json`
- Realtime HTTP surface: `https://gscdump.com/openapi/realtime.v1.json`

Generate Pydantic v2 models with `datamodel-code-generator`:

::pre{tabindex="0"}
```bash
pip install "datamodel-code-generator[http]" pydantic
datamodel-codegen \
  --url https://gscdump.com/openapi/analytics.v1.json \
  --input-file-type openapi \
  --output-model-type pydantic_v2.BaseModel \
  --output gscdump_analytics_models.py
```
::

Or generate a full `httpx`-based Python client with `openapi-python-client`:

::pre{tabindex="0"}
```bash
pip install openapi-python-client
openapi-python-client generate \
  --url https://gscdump.com/openapi/partner.v1.json \
  --output-path ./gscdump_partner_client
```
::

For offline builds or version-pinned specs, export the same OpenAPI documents locally from `@gscdump/contracts/v1`:

::pre{tabindex="0"}
```ts
import { writeFile } from 'node:fs/promises'
import { createGscdumpV1Documents } from '@gscdump/contracts/v1'

const documents = createGscdumpV1Documents()
await writeFile('openapi.analytics.v1.json', JSON.stringify(documents['openapi.analytics.v1.json'], null, 2))
await writeFile('openapi.partner.v1.json', JSON.stringify(documents['openapi.partner.v1.json'], null, 2))
```
::

Then pass `--input openapi.analytics.v1.json` to `datamodel-codegen` or `--path openapi.partner.v1.json` to `openapi-python-client generate`. Configure generated response models to ignore unknown keys so additive v1 fields stay compatible.

## Check the result

Run your script with valid `GSCDUMP_API_KEY` and `GSCDUMP_SITE_ID` values. Confirm the rows response prints `data.rows` and `meta.requestId`, and the Report response prints `data.totals` and `data.meta.syncStatus`. Test an invalid key to verify your error handler logs `code` and `requestId` without printing the API key. Continue with [Hosted analytics](https://gscdump.com/gscdump-sdk/guides/read-data/hosted-analytics) for Report semantics.

## Sitemap

See the full [sitemap](https://gscdump.com/sitemap.md) for all pages.
