Python 3.10+ · FastAPI · Data Science · AI Agents Sync & Async httpx + Pydantic v2 ~80% Token Savings (mode="summary") GDPR 0-PII · 0 Credits on 504/429

Python SDK & Async REST Quickstart
Production httpx + Pydantic Client & NDJSON Streams

Wire Python 3.10+, FastAPI backends, Jupyter data pipelines, and AI agents directly to EdgeData’s 67 REST endpoints (https://api.upp3.com) and 56 native Hosted MCP tools (https://mcp.upp3.com/mcp) across 16 global platforms. Includes sync & async httpx clients, 504/429 zero-charge backoff retries, Amazon NDJSON review streaming, and asyncio.gather LLM context batching with mode="summary" (~80% token savings).

Sync + Async
One module supports Jupyter scripts, FastAPI routes & asyncio.gather
NDJSON Streaming
Stream deep-bypass Amazon & TikTok reviews line-by-line with minimal RAM
~80% Less Tokens
mode="summary" packs multi-platform JSON cleanly into LLM prompts
0 Credits on 504/429
GDPR 0-PII scrubbed responses with zero-charge retries on upstream timeouts
Step 1 · Install Dependencies, OpenAPI 3.1 Export & Dual-Mode Client

pip install httpx pydantic & Drop In edgedata_client.py

Every Python snippet on this page is syntax-verified for Python 3.10+. Claim a free key in the wizard below and all code blocks update automatically with your live session key.

Install Runtime + Optional OpenAPI 3.1 Pydantic Model Export (67 Endpoints)
# 1) Install production HTTP + validation stack
pip install httpx pydantic

# 2) Optional: export live OpenAPI 3.1 schema (all 67 endpoints) & generate Pydantic v2 models
curl -sS https://api.upp3.com/v1/openapi-rapidapi.json -o edgedata-openapi.json
pip install datamodel-code-generator
datamodel-code-generator --input edgedata-openapi.json --input-file-type openapi --output edgedata_models.py --output-model-type pydantic_v2.BaseModel
edgedata_client.py Sync + Async · 504/429 Zero-Charge Retry · NDJSON
Python 3.10+ · httpx + Pydantic v2
from __future__ import annotations

import asyncio
import json
import os
import time
from collections.abc import AsyncIterator, Iterator
from typing import Any, Literal

import httpx
from pydantic import BaseModel, Field

EdgeDataMode = Literal["summary", "raw"]
RETRYABLE_STATUS = {429, 504}  # Strictly 0 Credits Charged on EdgeData


class EdgeDataMeta(BaseModel):
    channel: str | None = None
    plan: str | None = None
    items_returned: int | None = None
    credits_charged: int = 0
    credits_remaining: int | None = None
    elapsed_ms: int | None = None


class EdgeDataResponse(BaseModel):
    ok: bool = True
    source: str = ""
    mode: EdgeDataMode = "summary"
    data: dict[str, Any] = Field(default_factory=dict)
    meta: EdgeDataMeta = Field(default_factory=EdgeDataMeta)


class EdgeDataAPIError(RuntimeError):
    def __init__(self, status_code: int, message: str, payload: Any = None) -> None:
        super().__init__(f"EdgeData HTTP {status_code}: {message}")
        self.status_code = status_code
        self.payload = payload


def _build_headers(api_key: str, auth_header: Literal["X-API-Key", "Authorization"]) -> dict[str, str]:
    auth = (
        {"Authorization": f"Bearer {api_key}"}
        if auth_header == "Authorization"
        else {"X-API-Key": api_key}
    )
    return {"Accept": "application/json", **auth}


class EdgeDataClient:
    """Synchronous production EdgeData client with 504/429 zero-charge retries & NDJSON streaming."""

    def __init__(
        self,
        api_key: str | None = None,
        base_url: str = "https://api.upp3.com",
        auth_header: Literal["X-API-Key", "Authorization"] = "X-API-Key",
        max_retries: int = 3,
        timeout: float = 45.0,
    ) -> None:
        key = (api_key or os.getenv("EDGEDATA_API_KEY") or "YOUR_EDGEDATA_API_KEY").strip()
        self.max_retries = max_retries
        self._client = httpx.Client(
            base_url=base_url.rstrip("/"),
            headers=_build_headers(key, auth_header),
            timeout=timeout,
        )

    def __enter__(self) -> EdgeDataClient:
        return self

    def __exit__(self, *args: object) -> None:
        self.close()

    def close(self) -> None:
        self._client.close()

    def request(
        self,
        method: Literal["GET", "POST"],
        path: str,
        *,
        params: dict[str, Any] | None = None,
        json_body: dict[str, Any] | None = None,
    ) -> EdgeDataResponse:
        clean_params = {k: v for k, v in (params or {}).items() if v is not None}
        for attempt in range(self.max_retries + 1):
            resp = self._client.request(method, path, params=clean_params, json=json_body)
            if resp.status_code in RETRYABLE_STATUS and attempt < self.max_retries:
                retry_after = float(resp.headers.get("retry-after", "0") or 0)
                time.sleep(max(retry_after, 0.5 * (2**attempt)))
                continue  # HTTP 504/429 strictly incur 0 Credits Charged
            if resp.is_error:
                raise EdgeDataAPIError(resp.status_code, resp.text[:300])
            return EdgeDataResponse.model_validate(resp.json())
        raise EdgeDataAPIError(504, f"Exhausted retries on {path}")

    def get(self, path: str, params: dict[str, Any] | None = None) -> EdgeDataResponse:
        return self.request("GET", path, params=params)

    def post(self, path: str, json_body: dict[str, Any]) -> EdgeDataResponse:
        return self.request("POST", path, json_body=json_body)

    def stream_ndjson(self, path: str, json_body: dict[str, Any]) -> Iterator[dict[str, Any]]:
        with self._client.stream("POST", path, json=json_body) as resp:
            if resp.is_error:
                raise EdgeDataAPIError(resp.status_code, resp.read().decode("utf-8", "ignore")[:300])
            for line in resp.iter_lines():
                line = line.strip()
                if line:
                    yield json.loads(line)


class AsyncEdgeDataClient:
    """Asynchronous httpx client for FastAPI, AI agents, and asyncio.gather workloads."""

    def __init__(
        self,
        api_key: str | None = None,
        base_url: str = "https://api.upp3.com",
        auth_header: Literal["X-API-Key", "Authorization"] = "X-API-Key",
        max_retries: int = 3,
        timeout: float = 45.0,
    ) -> None:
        key = (api_key or os.getenv("EDGEDATA_API_KEY") or "YOUR_EDGEDATA_API_KEY").strip()
        self.max_retries = max_retries
        self._client = httpx.AsyncClient(
            base_url=base_url.rstrip("/"),
            headers=_build_headers(key, auth_header),
            timeout=timeout,
        )

    async def __aenter__(self) -> AsyncEdgeDataClient:
        return self

    async def __aexit__(self, *args: object) -> None:
        await self.aclose()

    async def aclose(self) -> None:
        await self._client.aclose()

    async def request(
        self,
        method: Literal["GET", "POST"],
        path: str,
        *,
        params: dict[str, Any] | None = None,
        json_body: dict[str, Any] | None = None,
    ) -> EdgeDataResponse:
        clean_params = {k: v for k, v in (params or {}).items() if v is not None}
        for attempt in range(self.max_retries + 1):
            resp = await self._client.request(method, path, params=clean_params, json=json_body)
            if resp.status_code in RETRYABLE_STATUS and attempt < self.max_retries:
                retry_after = float(resp.headers.get("retry-after", "0") or 0)
                await asyncio.sleep(max(retry_after, 0.5 * (2**attempt)))
                continue  # HTTP 504/429 strictly incur 0 Credits Charged
            if resp.is_error:
                raise EdgeDataAPIError(resp.status_code, resp.text[:300])
            return EdgeDataResponse.model_validate(resp.json())
        raise EdgeDataAPIError(504, f"Exhausted retries on {path}")

    async def get(self, path: str, params: dict[str, Any] | None = None) -> EdgeDataResponse:
        return await self.request("GET", path, params=params)

    async def post(self, path: str, json_body: dict[str, Any]) -> EdgeDataResponse:
        return await self.request("POST", path, json_body=json_body)

    async def astream_ndjson(self, path: str, json_body: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:
        async with self._client.stream("POST", path, json=json_body) as resp:
            if resp.is_error:
                body = await resp.aread()
                raise EdgeDataAPIError(resp.status_code, body.decode("utf-8", "ignore")[:300])
            async for line in resp.aiter_lines():
                line = line.strip()
                if line:
                    yield json.loads(line)
Step 01 · Dual Mode

Sync Scripts & Async FastAPI

Use EdgeDataClient in notebooks and cron scripts, or AsyncEdgeDataClient inside FastAPI routes and agent loops.

Step 02 · ~80% Token Savings

Pass mode="summary"

Server-side summary trimming removes raw HTML and image bloat before JSON ever hits your Pydantic models or LLM context.

Step 03 · Zero-Charge Retry

Automatic 504/429 Backoff

Upstream HTTP 504 timeouts and HTTP 429 rate limits strictly incur 0 Credits Charged, keeping retries free.

Step 2 · 4 Syntax-Verified Python Recipes

US/UK Real Estate, TradingView Finance, NDJSON Streaming & asyncio.gather

Every tab below uses exact live EdgeData REST routes and passes Python’s ast.parse syntax check. Switch tabs to copy runnable code for your pipeline.

examples/real_estate_us_uk.py (2 credits/call)
# examples/real_estate_us_uk.py — 4 US/UK Real Estate endpoints (2 credits/call, 0-PII)
import os
from edgedata_client import EdgeDataClient


def main() -> None:
    api_key = os.getenv("EDGEDATA_API_KEY", "YOUR_EDGEDATA_API_KEY")
    with EdgeDataClient(api_key=api_key) as client:
        # 1) Redfin US Residential Search (0-PII, mode="summary" saves ~81% tokens)
        redfin_homes = client.get(
            "/v1/real-estate/redfin/properties/search",
            params={
                "query": "Seattle, WA",
                "max_price": 950000,
                "min_beds": 3,
                "page_size": 10,
                "mode": "summary",
            },
        )

        # 2) Redfin US Metro Market Trends (median list/sale price & Days on Market)
        redfin_trends = client.get(
            "/v1/real-estate/redfin/market/trends",
            params={"query": "Seattle, WA", "mode": "summary"},
        )

        # 3) Rightmove UK Monthly House Price Index
        uk_hpi = client.get(
            "/v1/real-estate/rightmove/house-price-index",
            params={"mode": "summary"},
        )

        # 4) Rightmove UK Property Search (London BUY channel, GBP, 0-PII)
        uk_listings = client.get(
            "/v1/real-estate/rightmove/properties/search",
            params={
                "query": "London",
                "channel": "BUY",
                "max_price": 750000,
                "min_bedrooms": 2,
                "mode": "summary",
            },
        )

        print("Redfin median:", redfin_homes.data.get("median"), "credits:", redfin_homes.meta.credits_charged)
        print("Redfin DOM:", redfin_trends.data.get("median_days_on_market"))
        print("Rightmove HPI month:", uk_hpi.data.get("month"))
        print("London listings returned:", uk_listings.data.get("total_returned"))


if __name__ == "__main__":
    main()
Python Stack Client Class Streaming & Concurrency Best Practices
FastAPI / Starlette AsyncEdgeDataClient Share one client in FastAPI lifespan Reuse HTTP connection pool; return validated EdgeDataResponse
Jupyter / Pandas / Polars EdgeDataClient stream_ndjson() into DataFrames Use mode="raw" for tabular ETL or mode="summary" for rapid EDA
AI Agents / LangGraph AsyncEdgeDataClient asyncio.gather() across 16 platforms Always pass mode="summary" (~80% token savings) & 0-PII
Airflow / Prefect / Cron EdgeDataClient Auto retry on HTTP 504/429 Zero credit penalty on upstream timeouts; 6h warm cache cuts latency
Instant API Key · No Credit Card Required

Get 100 Free Monthly Credits for Python & FastAPI

Claim your EdgeData API key below in seconds. Once provisioned, edgedata_client.py and all 4 Python tabs above automatically inject your live key for copy-paste execution.

Transparent Upgrade Ladder · 67 REST + 56 MCP Tools

Simple Credits Built for Python Data Pipelines & Async Agents

One API key unlocks all 16 platforms. Upstream HTTP 504/429 errors strictly incur 0 Credits Charged.

No Card Required

Free Tier

$0 / month
  • ✓100 credits / mo via Free Key Wizard
  • ✓All 67 REST endpoints & 56 MCP tools
  • ✓mode="summary" ~80% token savings
Claim Free Key →
Never Expires

Credit Pack

$47 one-time
  • ✓25,000 non-expiring credits
  • ✓Zero recurring subscription lock-in
  • ✓Ideal for Kaggle, research & batch backfills
Buy $47 Pack →
Most Popular

Pro

$49 / month
  • ✓15,000 credits / mo · 60 RPM
  • ✓Up to 500 reviews/call + NDJSON stream
  • ✓HTTP 504/429 = 0 Credits Charged
Choose Pro ($49/mo) →
High Throughput

Scale

$149 / month
  • ✓60,000 credits / mo · 200 RPM
  • ✓Up to 2,000 reviews/call + priority routing
  • ✓Built for FastAPI & AsyncIO agent fleets
Choose Scale ($149/mo) →
Hosted Streamable HTTP MCP · Zero Local Python Server

Prefer No-Code / AI IDE MCP?

Skip writing Python tool wrappers when working inside AI coding IDEs or visual workflow builders. Reuse your exact same EdgeData API key with https://mcp.upp3.com/mcp to unlock all 56 Hosted MCP tools.

One API Key · 4 Developer Quickstarts

Explore the Other 3 SDK & REST Guides

Working across frontend, CLI, and LLM agent frameworks? Reuse your exact same EdgeData key below or return to the SDKs Index (/sdks).

Python SDK & Async REST FAQ

Frequently Asked Questions

Answers on httpx + Pydantic v2, Amazon NDJSON streaming, OpenAPI model generation, zero-charge retries, and token savings.

Why does EdgeData recommend httpx + Pydantic v2 for Python 3.10+?
httpx provides both synchronous and native asyncio HTTP clients with true line-by-line streaming for NDJSON endpoints like POST /v1/amazon/reviews/stream, while Pydantic v2 validates response envelopes and integrates cleanly with FastAPI and modern AI agent frameworks.
How does NDJSON streaming work for Amazon reviews in Python?
POST /v1/amazon/reviews/stream emits newline-delimited JSON objects as deep-bypass pages arrive. Using client.stream("POST", ...) with iter_lines() lets your script process hundreds of reviews incrementally with minimal memory overhead.
How can I generate typed Pydantic models for all 67 EdgeData REST endpoints?
Download the live OpenAPI 3.1 specification from https://api.upp3.com/v1/openapi-rapidapi.json and run datamodel-code-generator --input edgedata-openapi.json --output edgedata_models.py --output-model-type pydantic_v2.BaseModel.
Are retries on HTTP 504 or HTTP 429 safe for my credit balance?
Yes. Upstream HTTP 504 timeouts and HTTP 429 rate-limit responses strictly incur 0 Credits Charged on EdgeData, so exponential backoff inside EdgeDataClient and AsyncEdgeDataClient never wastes your quota.
How much context does mode="summary" save when feeding asyncio.gather results into LLMs?
Setting mode="summary" trims noisy HTML, raw image arrays, and rendering metadata server-side across all 16 platforms, reducing input tokens by ~80% on average while enforcing strict GDPR 0-PII compliance.