Retries, idempotency, pages and rate limits
A small client that retries safely, pages through lists and stays under the limit.
15 minScope: readWhat you get
- Writes that never run twice, whatever the network does.
- A loop over every merchant, page by page.
- A client that stays under 120 requests a minute.
Send an Idempotency-Key on every write
On every
POSTandPATCH, send a new UUID asIdempotency-Keyand keep it for the retries of that request. The same key and the same request answer the first answer again, withIdempotent-Replayed: true. The same key with another body is422 idempotency_mismatch; while the first is still running,409 idempotency_in_progress.curl -X PATCH "https://aikvali.com/api/v1/merchants/3f0c2a52-6a1e-4c1b-9d55-2f7f5b1e9a10" \ -H "Authorization: Bearer $KVALI_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{"status":"live"}'const res = await fetch("https://aikvali.com/api/v1/merchants/3f0c2a52-6a1e-4c1b-9d55-2f7f5b1e9a10", { method: "PATCH", headers: { Authorization: `Bearer ${process.env.KVALI_KEY}`, "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() }, body: JSON.stringify({ "status": "live" }), }); if (!res.ok) throw new Error((await res.json()).error.message); const { data } = await res.json();import os, uuid import requests res = requests.patch( "https://aikvali.com/api/v1/merchants/3f0c2a52-6a1e-4c1b-9d55-2f7f5b1e9a10", headers={"Authorization": f"Bearer {os.environ['KVALI_KEY']}", "Idempotency-Key": str(uuid.uuid4())}, json={ "status": "live", }, timeout=30, ) if not res.ok: raise RuntimeError(res.json()["error"]["message"]) data = res.json()["data"]Retry only what is safe to retry
429and5xxare safe to retry; any other4xxmeans fix the request. On429, waitRetry-Afterseconds. Every answer carriesRateLimit-Limit(120 a minute per key),RateLimit-RemainingandRateLimit-Reset.const BASE = "https://aikvali.com/api/v1"; export async function kvali(path, { method = "GET", body } = {}) { const idempotencyKey = method === "GET" ? undefined : crypto.randomUUID(); // one key for every retry for (let attempt = 1; ; attempt++) { const res = await fetch(BASE + path, { method, headers: { Authorization: "Bearer " + process.env.KVALI_KEY, ...(body && { "Content-Type": "application/json" }), ...(idempotencyKey && { "Idempotency-Key": idempotencyKey }) }, body: body && JSON.stringify(body), }); if (res.ok) return res.json(); const retry = res.status === 429 || res.status >= 500; if (!retry || attempt === 5) throw new Error((await res.json()).error.code); const wait = Number(res.headers.get("Retry-After")) || 2 ** attempt; await new Promise((r) => setTimeout(r, wait * 1000)); } }import os, time, uuid import requests BASE = "https://aikvali.com/api/v1" def kvali(path, method="GET", body=None): headers = {"Authorization": f"Bearer {os.environ['KVALI_KEY']}"} if method != "GET": headers["Idempotency-Key"] = str(uuid.uuid4()) # one key for every retry for attempt in range(1, 6): res = requests.request(method, BASE + path, headers=headers, json=body, timeout=30) if res.ok: return res.json() if res.status_code != 429 and res.status_code < 500 or attempt == 5: raise RuntimeError(res.json()["error"]["code"]) time.sleep(float(res.headers.get("Retry-After") or 2 ** attempt))Page through a list
Lists return at most 100 rows a page (
limit, default 25). Merchants and reviews run newest first: pass the last page'snext_beforeasbefore. The monitoring lists and violations usesinceandnext_cursorinstead (see the monitoring recipe).let before = null; do { const page = await kvali("/merchants?limit=100" + (before ? "&before=" + encodeURIComponent(before) : "")); for (const m of page.data) console.log(m.id, m.legal_name, m.health.verdict); before = page.next_before; } while (before);before = None while True: page = kvali("/merchants?limit=100" + (f"&before={before}" if before else "")) for m in page["data"]: print(m["id"], m["legal_name"], m["health"]["verdict"]) before = page["next_before"] if not before: break