import os
import time
import uuid
import requests
def get_with_retry(path: str, max_attempts: int = 4) -> dict:
for attempt in range(1, max_attempts + 1):
request_id = str(uuid.uuid4())
resp = requests.get(
f"https://api.opentype.dev{path}",
headers={
"Authorization": f"Bearer {os.environ['OPENTYPE_API_KEY']}",
"x-request-id": request_id, # log it; quote it if the problem persists
},
timeout=30,
)
if resp.ok:
return resp.json()
try:
code = resp.json()["error"]["code"]
except ValueError:
code = f"HTTP {resp.status_code}"
print(f"GET {path} -> {resp.status_code} {code} ({request_id})")
if resp.status_code < 500 or attempt == max_attempts:
raise RuntimeError(f"{code} ({request_id})")
time.sleep(2 ** attempt)
data = get_with_retry("/v1/usage/ledger?limit=50") # needs usage_read