Docs · for developers
API examples
Code you can copy: a first call with an API key, reading every page of a list, retrying safely, and checking that a webhook came from Emrg.
The rules these follow (keys, pages, errors, limits) are in the API overview; every operation is in the API reference.
A first call
Create a key in Emrg under Settings › API keys. It is shown once.
# Your key, from Settings → API keys in the Emrg app.
export EMRG_API_KEY="emrg_sk_..."
# Read: the first page of contacts.
curl "https://app.emrg.ai/v1/contacts?limit=25" \
-H "Authorization: Bearer $EMRG_API_KEY"
# Write: add a contact. Sending the same Idempotency-Key again
# returns the first answer instead of adding a second contact.
curl -X POST "https://app.emrg.ai/v1/contacts" \
-H "Authorization: Bearer $EMRG_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: new-lead-sam-2026-11-17" \
-d '{"firstName": "Sam", "email": "sam@example.com"}'
Every page, and safe retries
Each client follows nextCursor until it is null, keeping any filters you gave. It waits as long as Retry-After says after a 429, which ran nothing, and retries a read after a server error. It never repeats a write by itself: after a server error, send the same call again with the same Idempotency-Key, and Emrg returns the first answer instead of adding a second contact (the reference marks the writes that do; creating an API key doesn't). Errors carry the answer's x-request-id: quote it when you write to support.
// A small client for Emrg's API (Node 18+, Deno, Bun or a Cloudflare Worker).
const API = "https://app.emrg.ai/v1";
/** Seconds to wait from a Retry-After header: a number of seconds or an HTTP date. */
function retryAfterSeconds(value, fallback) {
if (value === null) return fallback;
if (/^\d+$/.test(value)) return Number(value);
const at = Date.parse(value);
return Number.isNaN(at) ? fallback : Math.max(0, (at - Date.now()) / 1000);
}
/**
* One call. A 429 ran nothing, so it is retried after Retry-After; a read is also retried after a
* server error. A write is never repeated here: if it fails with a server error, send it again
* yourself with the same Idempotency-Key (the reference marks the writes that return their first
* answer for a repeated key; creating an API key, for one, doesn't).
*/
export async function call(
method,
path,
{ apiKey, body, idempotencyKey, fetch = globalThis.fetch } = {},
) {
const headers = { Authorization: `Bearer ${apiKey}` };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
for (let attempt = 1; ; attempt++) {
const response = await fetch(`${API}${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
const retry = response.status === 429 || (response.status >= 500 && method === "GET");
if (retry && attempt < 5) {
const seconds = retryAfterSeconds(response.headers.get("Retry-After"), 2 ** attempt);
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
continue;
}
const requestId = response.headers.get("x-request-id");
const text = await response.text();
let answer;
try {
answer = JSON.parse(text);
} catch {
// A proxy's error page, not Emrg's JSON.
throw new Error(`HTTP ${response.status} (request ${requestId})`);
}
if (!response.ok) {
const { code, message, fix } = answer.error;
throw new Error(`${code}: ${message} ${fix} (HTTP ${response.status}, request ${requestId})`);
}
return answer.data;
}
}
/** Every item of a list, page by page, following nextCursor until it is null. */
export async function listAll(path, options) {
const url = new URL(path, API);
url.searchParams.set("limit", "100");
const items = [];
let cursor = null;
do {
if (cursor) url.searchParams.set("cursor", cursor);
const page = await call("GET", `${url.pathname}${url.search}`, options);
items.push(...page.items);
cursor = page.nextCursor;
} while (cursor);
return items;
}
// Example:
// const contacts = await listAll("/contacts?search=Sam", { apiKey: process.env.EMRG_API_KEY });
// await call("POST", "/contacts", {
// apiKey: process.env.EMRG_API_KEY,
// body: { firstName: "Sam", email: "sam@example.com" },
// idempotencyKey: "new-lead-sam-2026-11-17",
// });
# A small client for Emrg's API, standard library only (Python 3.9+).
import email.utils
import json
import time
import urllib.error
import urllib.parse
import urllib.request
API = "https://app.emrg.ai/v1"
def retry_after_seconds(value, fallback):
"""Seconds to wait from a Retry-After header: a number of seconds or an HTTP date."""
if value is None:
return fallback
if value.isdigit():
return int(value)
try:
return max(0, email.utils.parsedate_to_datetime(value).timestamp() - time.time())
except (TypeError, ValueError):
return fallback
def call(method, path, api_key, body=None, idempotency_key=None):
"""One call. A 429 ran nothing, so it is retried after Retry-After; a read is also retried
after a server error. A write is never repeated here: if it fails with a server error, send
it again yourself with the same Idempotency-Key (the reference marks the writes that return
their first answer for a repeated key; creating an API key, for one, doesn't)."""
headers = {"Authorization": f"Bearer {api_key}"}
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in range(1, 6):
request = urllib.request.Request(API + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request) as response:
return json.load(response)["data"]
except urllib.error.HTTPError as refusal:
retry = refusal.code == 429 or (refusal.code >= 500 and method == "GET")
if retry and attempt < 5:
time.sleep(retry_after_seconds(refusal.headers.get("Retry-After"), 2**attempt))
continue
request_id = refusal.headers.get("x-request-id")
try:
error = json.load(refusal)["error"]
except (ValueError, KeyError, TypeError):
# A proxy's error page, not Emrg's JSON.
raise RuntimeError(f"HTTP {refusal.code} (request {request_id})") from None
raise RuntimeError(
f"{error['code']}: {error['message']} {error['fix']}"
f" (HTTP {refusal.code}, request {request_id})"
) from None
def list_all(path, api_key):
"""Every item of a list, page by page, following nextCursor until it is None."""
parts = urllib.parse.urlsplit(path)
query = dict(urllib.parse.parse_qsl(parts.query))
query["limit"] = 100
items = []
while True:
page = call("GET", f"{parts.path}?{urllib.parse.urlencode(query)}", api_key)
items += page["items"]
if page["nextCursor"] is None:
return items
query["cursor"] = page["nextCursor"]
# Example:
# contacts = list_all("/contacts?search=Sam", os.environ["EMRG_API_KEY"])
# call("POST", "/contacts", os.environ["EMRG_API_KEY"],
# body={"firstName": "Sam", "email": "sam@example.com"},
# idempotency_key="new-lead-sam-2026-11-17")
Checking a webhook
Check every event before acting on it, with the standardwebhooks library for JavaScript or Python. Give it the raw body, exactly as it arrived: parsing and re-encoding the JSON first changes the bytes, and the signature no longer matches. A delivery can arrive twice, so act on each webhook-id once.
// npm install standardwebhooks
import { Webhook } from "standardwebhooks";
/**
* Checks an event from Emrg, then hands it to `handle` with its delivery id. `secret` is the
* whsec_ secret Settings showed when you added the webhook. Answer 2xx quickly: queue slow work
* rather than doing it here.
*/
export async function receive(request, secret, handle) {
const body = await request.text(); // the raw body, before any JSON parsing
const headers = {
"webhook-id": request.headers.get("webhook-id") ?? "",
"webhook-timestamp": request.headers.get("webhook-timestamp") ?? "",
"webhook-signature": request.headers.get("webhook-signature") ?? "",
};
let event;
try {
event = new Webhook(secret).verify(body, headers);
} catch {
// A wrong or malformed signature, or a timestamp more than five minutes off.
return new Response("Invalid signature", { status: 400 });
}
// The same delivery can arrive twice (if your 2xx was lost, Emrg tries again with the same
// webhook-id): in `handle`, record the id and act only if it wasn't recorded before, in one
// step (a unique key in your database), so a repeat does nothing.
await handle(event, headers["webhook-id"]);
return new Response(null, { status: 204 });
}
# pip install standardwebhooks
from standardwebhooks.webhooks import Webhook, WebhookVerificationError
def receive(body: bytes, request_headers, secret: str):
"""Checks an event from Emrg before acting on it.
body is the raw request body, before any JSON parsing; secret is the whsec_ secret
Settings showed when you added the webhook. Returns (event, delivery_id), or None to
answer 400.
"""
headers = {
name: request_headers.get(name, "")
for name in ("webhook-id", "webhook-timestamp", "webhook-signature")
}
try:
event = Webhook(secret).verify(body, headers)
except (WebhookVerificationError, ValueError):
# A wrong or malformed signature or body, or a timestamp more than five minutes off.
return None
# The same delivery can arrive twice (if your 2xx was lost, Emrg tries again with the same
# webhook-id): record the id and act only if it wasn't recorded before, in one step (a
# unique key in your database), so a repeat does nothing.
return event, headers["webhook-id"]
A typed client
There is no Emrg SDK to install: generate types from the OpenAPI document instead, for example with openapi-typescript and call it with openapi-fetch:
npx openapi-typescript https://app.emrg.ai/v1/openapi.json -o emrg.d.ts