Skip to content

Examples and recipes

These examples use plain HTTP so they work in any environment that can send HTTPS requests.

Set the key once:

Terminal window
export AFTERLIB_API_KEY="al_live_replace_me"

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);

This example uses Python’s standard library:

import json
import os
import urllib.error
import 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"])

Use GET /v1/credits before a workflow that may return many ads or pages:

Terminal window
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.

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.

  1. Save error.requestId from the error response or the X-Afterlib-Request-Id response header.
  2. Open the Developer Portal request log.
  3. Compare the method, path, status, operation, credit charge, and key prefix.
  4. Include the request ID when asking support to investigate.