Credits and idempotency
How credits work
Section titled “How credits work”- You get credits from a plan (each billing period), credit packs, promotions, or a grant from us. Each grant is a lot with its own expiry date. Spending always uses the lot that expires soonest first.
- Credits are whole numbers. Money is never charged per call: you buy credits in the portal (Billing) and calls spend them.
- Free:
whoami,estimate,credits,ledger,usage, fields, taxonomy and geo lookups, and (when live) search and count. - Charged:
unlockandenrich, per bundle delivered. Enrich charges only on a match. A bundle is charged only if the record has a value for it: a person with no mobile number isn’t charged formobile. - Owned records are free again. Once you pay for a bundle of a record, fetching it again is free for the re-access period of your rate card (365 days by default).
- Test keys never spend credits. They report what a live key would pay in
meta.credits_would_charge.
Spending calls answer with the cost in meta.credits_charged and meta.credits_remaining, and in the
Zemo-Credits-Charged and Zemo-Credits-Remaining headers.
Limits that stop a charge
Section titled “Limits that stop a charge”| Code | When |
|---|---|
402 credits.insufficient |
Not enough available credits (credits reserved for bulk jobs don’t count) |
402 credits.max_exceeded |
The call would cost more than your max_credits |
402 credits.cap_reached |
The key’s daily credit cap is used up (resets at midnight UTC) |
402 quota.exhausted |
A product with a records quota used this period’s quota |
In every case nothing is charged.
Idempotency-Key
Section titled “Idempotency-Key”Every spending call (POST /v1/unlock, /v1/person/enrich, /v1/company/enrich) needs an
Idempotency-Key header: 8 to 128 characters, unique per logical request. A UUID is a good choice.
- Same key, same body within 24 hours: you get the stored answer back with
meta.replayed: true, and nothing is charged again. Retry with the same key after a timeout or a network error. - Same key, different body:
409 idempotency.mismatch. Use a new key for a new request. - Same key while the first request is still running:
409 idempotency.in_progress. Wait a moment and retry. - No key:
400 idempotency.missing, before anything is charged.
Test keys need the header too, but don’t store answers: a retry is answered afresh (and is free).
The unlock sample estimates first, unlocks with a key, and retries with the same key:
"""Estimate the cost (free), then unlock records by ID with an Idempotency-Key.
Test keys (zd_test_…) read the test dataset and never spend credits:meta.credits_would_charge shows what a live key would pay."""
import jsonimport osimport urllib.requestimport uuid
BASE = os.environ.get("ZEMO_API_BASE", "https://api.zemodata.com")SECRET = os.environ["ZEMO_API_KEY"]
def post(path: str, body: dict, idempotency_key: str = "") -> dict: headers = {"Authorization": f"Bearer {SECRET}", "Content-Type": "application/json"} if idempotency_key: headers["Idempotency-Key"] = idempotency_key request = urllib.request.Request( f"{BASE}{path}", data=json.dumps(body).encode(), headers=headers, method="POST" ) with urllib.request.urlopen(request, timeout=30) as response: return json.load(response)
body = { "entity": "person", "product": os.environ.get("ZEMO_PRODUCT", "demo-people"), "ids": [os.environ["ZEMO_RECORD_ID"]], # up to 100 IDs per call "bundles": ["profile", "work_email"], "max_credits": 50, # never pay more than this for the call}
estimate = post("/v1/estimate", body)["data"]print("estimate:", estimate["credits"], "credits")
key = str(uuid.uuid4()) # one key per logical request; reuse it only to retry the same requestresult = post("/v1/unlock", body, idempotency_key=key)meta = result["meta"]print("charged:", meta["credits_charged"], "would charge:", meta.get("credits_would_charge"))for item in result["data"]["records"]: emails = item["record"].get("emails", {}).get("work", []) print(item["id"], item["record"]["name"]["full"], [email["value"] for email in emails])for rejected in result["data"]["rejected"]: print("not delivered:", rejected["id"], rejected["reason"])
# With a live key, a retry with the same key and body returns the stored answer and charges# nothing again (meta.replayed is true). Test keys answer afresh each time, also for free.again = post("/v1/unlock", body, idempotency_key=key)print("replayed:", again["meta"].get("replayed"))// Estimate the cost (free), then unlock records by ID with an Idempotency-Key.// Test keys (zd_test_…) read the test dataset and never spend credits:// meta.credits_would_charge shows what a live key would pay.import { randomUUID } from "node:crypto";
const BASE = process.env.ZEMO_API_BASE ?? "https://api.zemodata.com";
async function post(path, body, idempotencyKey) { const headers = { Authorization: `Bearer ${process.env.ZEMO_API_KEY}`, "Content-Type": "application/json" }; if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey; const response = await fetch(`${BASE}${path}`, { method: "POST", headers, body: JSON.stringify(body) }); if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`); return response.json();}
const body = { entity: "person", product: process.env.ZEMO_PRODUCT ?? "demo-people", ids: [process.env.ZEMO_RECORD_ID], // up to 100 IDs per call bundles: ["profile", "work_email"], max_credits: 50, // never pay more than this for the call};
const estimate = (await post("/v1/estimate", body)).data;console.log("estimate:", estimate.credits, "credits");
const key = randomUUID(); // one key per logical request; reuse it only to retry the same requestconst result = await post("/v1/unlock", body, key);console.log("charged:", result.meta.credits_charged, "would charge:", result.meta.credits_would_charge);for (const item of result.data.records) { const emails = item.record.emails?.work ?? []; console.log(item.id, item.record.name.full, emails.map((email) => email.value));}for (const rejected of result.data.rejected) console.log("not delivered:", rejected.id, rejected.reason);
// With a live key, a retry with the same key and body returns the stored answer and charges// nothing again (meta.replayed is true). Test keys answer afresh each time, also for free.const again = await post("/v1/unlock", body, key);console.log("replayed:", again.meta.replayed ?? null);# Estimate the cost (free), then unlock records by ID with an Idempotency-Key.# Test keys (zd_test_…) never spend credits: meta.credits_would_charge shows what a live key would pay.set -euo pipefailBASE="${ZEMO_API_BASE:-https://api.zemodata.com}"PRODUCT="${ZEMO_PRODUCT:-demo-people}"
body="{\"entity\": \"person\", \"product\": \"$PRODUCT\", \"ids\": [\"$ZEMO_RECORD_ID\"], \"bundles\": [\"profile\", \"work_email\"], \"max_credits\": 50}"
curl --silent --show-error --fail-with-body \ -H "Authorization: Bearer $ZEMO_API_KEY" -H "Content-Type: application/json" \ -d "$body" "$BASE/v1/estimate"echo
key="unlock-$(date +%s)-$RANDOM" # one key per logical request; reuse it only to retry itfor attempt in first retry; do answer="$(curl --silent --show-error --fail-with-body \ -H "Authorization: Bearer $ZEMO_API_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: $key" \ -d "$body" "$BASE/v1/unlock")" echo "$answer"done# On the retry a live key gets the stored answer, charged once ("replayed": true).# Test keys answer afresh each time, also for free.echo "replayed: $(printf '%s' "$answer" | sed -n 's/.*"replayed": *\([a-z]*\).*/\1/p')"Balance and history
Section titled “Balance and history”GET /v1/credits (scope ledger_read) answers your balance, held (reserved for bulk jobs),
available (balance − held), the open lots with their expiry, and product quotas.
GET /v1/ledger lists every change to the balance, newest first: kind (trial, plan_grant,
pack_purchase, promo, grant, removal, spend, refund, expiry, adjustment), delta,
balance_after, who made it (by), the key and product, and a
reference such as the request ID. Filter with from, to, kind, key_id and product; page with
cursor (see Pagination). Send Accept: text/csv for a CSV of the same rows.
The history is append-only: a correction is a new entry, never an edit.
"""Read the credit balance, then page through the credit history with the cursor."""
import jsonimport osimport urllib.parseimport urllib.request
BASE = os.environ.get("ZEMO_API_BASE", "https://api.zemodata.com")HEADERS = {"Authorization": f"Bearer {os.environ['ZEMO_API_KEY']}"} # needs the ledger_read scope
def get(path: str, **params: str) -> dict: query = urllib.parse.urlencode({key: value for key, value in params.items() if value}) request = urllib.request.Request(f"{BASE}{path}?{query}", headers=HEADERS) with urllib.request.urlopen(request, timeout=30) as response: return json.load(response)
balance = get("/v1/credits")["data"]print(f"balance {balance['balance']}, reserved {balance['held']}, available {balance['available']}")for lot in balance["lots"]: print(f" {lot['remaining']} {lot['kind']} credits, expire {lot['expires_at'] or 'never'}")
# Newest first. Keep asking with meta.next_cursor until it is null.cursor, entries = "", 0while True: page = get("/v1/ledger", limit="50", cursor=cursor) for entry in page["data"]: entries += 1 print( f" {entry['created_at']} {entry['kind']:<10} {entry['delta']:>+6} -> {entry['balance_after']}" ) cursor = page["meta"]["next_cursor"] if not cursor: breakprint(entries, "history entries")// Read the credit balance, then page through the credit history with the cursor.
const BASE = process.env.ZEMO_API_BASE ?? "https://api.zemodata.com";const headers = { Authorization: `Bearer ${process.env.ZEMO_API_KEY}` }; // needs the ledger_read scope
async function get(path, params = {}) { const query = new URLSearchParams(Object.entries(params).filter(([, value]) => value)); const response = await fetch(`${BASE}${path}?${query}`, { headers }); if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`); return response.json();}
const { data: balance } = await get("/v1/credits");console.log(`balance ${balance.balance}, reserved ${balance.held}, available ${balance.available}`);for (const lot of balance.lots) { console.log(` ${lot.remaining} ${lot.kind} credits, expire ${lot.expires_at ?? "never"}`);}
// Newest first. Keep asking with meta.next_cursor until it is null.let cursor = "";let entries = 0;do { const page = await get("/v1/ledger", { limit: "50", cursor }); for (const entry of page.data) { entries += 1; console.log(` ${entry.created_at} ${entry.kind.padEnd(10)} ${entry.delta} -> ${entry.balance_after}`); } cursor = page.meta.next_cursor;} while (cursor);console.log(entries, "history entries");# Read the credit balance, then page through the credit history with the cursor.set -euo pipefailBASE="${ZEMO_API_BASE:-https://api.zemodata.com}"AUTH="Authorization: Bearer $ZEMO_API_KEY" # needs the ledger_read scope
curl --silent --show-error --fail-with-body -H "$AUTH" "$BASE/v1/credits"echo
# Newest first. Keep asking with meta.next_cursor until it is null.cursor=""pages=0while :; do page="$(curl --silent --show-error --fail-with-body -H "$AUTH" -G "$BASE/v1/ledger" \ --data-urlencode "limit=50" ${cursor:+--data-urlencode "cursor=$cursor"})" echo "$page" pages=$((pages + 1)) cursor="$(printf '%s' "$page" | sed -n 's/.*"next_cursor": *"\([^"]*\)".*/\1/p')" [ -n "$cursor" ] || breakdoneecho "$pages page(s) of history entries"