Examples and recipes
These examples use plain HTTP so they work in any environment that can send HTTPS requests.
Set the key once:
export AFTERLIB_API_KEY="al_live_replace_me"JavaScript and TypeScript
Section titled “JavaScript and TypeScript”Use fetch directly:
const apiKey = process.env.AFTERLIB_API_KEY;
if (!apiKey) { throw new Error('AFTERLIB_API_KEY is required');}
const response = await fetch('https://api.afterlib.com/v1/ads/search', { method: 'POST', headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'X-Afterlib-Client': 'example-fetch/1.0', }, body: JSON.stringify({ query: 'running shoes', limit: 10, }),});
const body = await response.json();
if (!response.ok) { console.error(body.error?.requestId, body.error?.code, body.error?.message); throw new Error('AfterLib request failed');}
console.log(body.items);Python
Section titled “Python”This example uses Python’s standard library:
import jsonimport osimport urllib.errorimport urllib.request
api_key = os.environ["AFTERLIB_API_KEY"]
request = urllib.request.Request( "https://api.afterlib.com/v1/pages/search", data=json.dumps({"query": "coffee", "limit": 10}).encode("utf-8"), method="POST", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "X-Afterlib-Client": "example-python/1.0", },)
try: with urllib.request.urlopen(request) as response: body = json.loads(response.read().decode("utf-8"))except urllib.error.HTTPError as error: body = json.loads(error.read().decode("utf-8")) response_error = body.get("error", {}) print(response_error.get("requestId"), response_error.get("code"), response_error.get("message")) raise
print(body["items"])Check credits before search
Section titled “Check credits before search”Use GET /v1/credits before a workflow that may return many ads or pages:
curl https://api.afterlib.com/v1/credits \ -H "Authorization: Bearer $AFTERLIB_API_KEY"If the remaining balance is low, lower limit, narrow the search query, or wait for the next billing period.
Handle credit and limit errors
Section titled “Handle credit and limit errors”Treat both 402 and 429 as stop signals for the current workflow. Do not immediately retry the same credit-consuming request.
if (response.status === 402 || response.status === 429) { const body = await response.json(); console.error('AfterLib credits or limits blocked the request', { code: body.error?.code, requestId: body.error?.requestId, });}402 means the account needs an active subscription or available credits. 429 means a usage limit has been reached.
Debug a failed request
Section titled “Debug a failed request”- Save
error.requestIdfrom the error response or theX-Afterlib-Request-Idresponse header. - Open the Developer Portal request log.
- Compare the method, path, status, operation, credit charge, and key prefix.
- Include the request ID when asking support to investigate.