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.
# 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
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)
Sync Scripts & Async FastAPI
Use EdgeDataClient in notebooks and cron scripts, or AsyncEdgeDataClient inside FastAPI routes and agent loops.
Pass mode="summary"
Server-side summary trimming removes raw HTML and image bloat before JSON ever hits your Pydantic models or LLM context.
Automatic 504/429 Backoff
Upstream HTTP 504 timeouts and HTTP 429 rate limits strictly incur 0 Credits Charged, keeping retries free.