import os, time, httpx
BASE = "https://api.voice.wixzel.com"
class WixzelError(RuntimeError):
def __init__(self, code, message, request_id):
super().__init__(f"{code}: {message}")
self.code, self.request_id = code, request_id
def wixzel(path, method="GET", body=None, idempotency_key=None, attempts=3):
headers = {"Authorization": f"Bearer {os.environ['WIXZEL_API_KEY']}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in range(attempts):
res = httpx.request(method, f"{BASE}{path}", headers=headers, json=body)
# A 429 did no work, so it is safe to repeat. A 4xx will fail the same
# way with the same body.
if res.status_code == 429 and attempt < attempts - 1:
time.sleep(float(res.headers.get("Retry-After", 1)))
continue
if res.status_code == 204:
return None
data = res.json()
if res.status_code >= 400:
err = data["error"]
raise WixzelError(err["code"], err["message"], err["request_id"])
return data