Error Handling

Every error code the API returns, and how to handle it. Errors never cost credits.

Error Response Format

All errors share the same JSON structure, at the top level of the body (never wrapped in another object): a stable machine-readable error code, a human-readable message and, when there is more to say, a details object. Branch on error: messages are meant for people and may change.

  • 400 invalid_parameter puts the offending parameter in details.param.
  • 402 insufficient_credits carries details.available and details.required when you have some credits but fewer than the call needs.
  • Both 429 errors add a top-level retry_after (seconds) and the Retry-After header.
  • An unknown path answers 404 not_found and a wrong method 405 method_not_allowed, in the same shape.
JSON
{
  "error": "invalid_parameter",
  "message": "country must be an ISO 3166-1 alpha-2 code or ALL",
  "details": { "param": "country" }
}

Error Codes

HTTPerrorMeaningRetry?
400invalid_parameterA parameter is missing or invalid; details.param names itNo: fix the request
400cursor_mismatchThe cursor was used with different parameters than the request that produced itNo: repeat the original parameters or drop the cursor
401missing_api_keyNo API key in X-API-Key or AuthorizationNo
401invalid_api_keyThe API key does not exist or was revokedNo
402insufficient_creditsThe account has no credits leftAfter a top-up or when the free tier resets
404ad_not_foundNo ad with this ID in the Ad LibraryNo
404page_not_foundNo advertiser page with this IDNo
404not_foundUnknown path (check the URL and the /v1 prefix)No
405method_not_allowedEvery endpoint is GETNo
410cursor_expiredThe cursor is older than 1 hourRestart from the first page
429rate_limit_exceededToo many requests for this API keyYes, after the Retry-After header
429insufficient_credits_retry_laterThe key kept retrying with no credits and is pausedAfter Retry-After, or right after a top-up
502upstream_schema_changedThe Ad Library changed its format; we are alerted automaticallyLater
503upstream_unavailableThe Ad Library is temporarily unreachable (temporary block, all fetchers failed)Yes, with exponential backoff
504upstream_timeoutThe Ad Library did not answer in timeYes, with backoff
500internal_server_errorUnexpected error on our sideYes, with backoff

HTTP Status Codes

400

Bad Request

A parameter is missing or invalid, or a cursor was reused with different parameters.

Resolution

Fix the request: details.param names the offending parameter. With cursor_mismatch, send exactly the parameters of the request that returned the cursor.

Example Response

{
  "error": "invalid_parameter",
  "message": "country must be an ISO 3166-1 alpha-2 code or ALL",
  "details": { "param": "country" }
}
401

Unauthorized

The API key is missing, does not exist or has been revoked.

Resolution

Send a valid key in X-API-Key or Authorization: Bearer. Create a new one in the dashboard if needed.

Example Response

{
  "error": "invalid_api_key",
  "message": "Invalid or inactive API key."
}
402

Payment Required

The account has no credits left.

Resolution

Buy credits on the Billing page (they never expire) or wait for the 100 free credits of next month.

Example Response

{
  "error": "insufficient_credits",
  "message": "Insufficient credits. Please purchase more credits."
}
404

Not Found

The ad or the advertiser page does not exist in the Ad Library (ad_not_found, page_not_found).

Resolution

Check the ID. Do not retry: the answer will not change.

Example Response

{
  "error": "ad_not_found",
  "message": "Ad 123 not found in the Ad Library"
}
410

Gone

The cursor has expired (cursors are valid for 1 hour).

Resolution

Start again from the first page, without the cursor.

Example Response

{
  "error": "cursor_expired",
  "message": "Cursor expired or unknown. Restart the search."
}
429

Too Many Requests

Too many requests from this API key (rate_limit_exceeded), or a key that keeps retrying with no credits has been paused (insufficient_credits_retry_later).

Resolution

Wait the number of seconds in the Retry-After header, then retry. A top-up lifts insufficient_credits_retry_later within seconds.

Example Response

{
  "error": "rate_limit_exceeded",
  "message": "Rate limit exceeded. Maximum 300 requests per minute.",
  "retry_after": 12
}
502

Bad Gateway

The Meta Ad Library changed the format of its data and we could not read it safely (upstream_schema_changed). We get an alert and fix it; we never return half-parsed data.

Resolution

Retry later.

Example Response

{
  "error": "upstream_schema_changed",
  "message": "The Ad Library changed its format; we have been alerted (not billed)."
}
503

Service Unavailable

The Ad Library is temporarily unreachable (upstream_unavailable).

Resolution

Retry with exponential backoff (1 s, 2 s, 4 s…).

Example Response

{
  "error": "upstream_unavailable",
  "message": "The Ad Library is temporarily unavailable. Retry in a few seconds (not billed)."
}
504

Gateway Timeout

The Ad Library did not answer in time (upstream_timeout).

Resolution

Retry with exponential backoff, possibly with a smaller limit.

Example Response

{
  "error": "upstream_timeout",
  "message": "The Ad Library did not answer in time. Retry (not billed)."
}
500

Internal Server Error

An unexpected error on our side (internal_server_error).

Resolution

Retry with backoff. If it persists, contact support with the time of the request.

Example Response

{
  "error": "internal_server_error",
  "message": "An unexpected error occurred. Please try again later."
}

Errors Are Never Billed

Only 2xx responses consume credits, and an empty result list costs nothing. If a key keeps retrying after 402 insufficient_credits, it gets 429 insufficient_credits_retry_later with a Retry-After header for a while; topping up from the Billing page lifts the pause within seconds.

Error Handling Best Practices

1. Branch on the error code, not on the message

The error codes are stable; messages may change.

Python
r = requests.get("https://api.scrapeadlibrary.com/v1/ads/search", params={"q": "nike"},
                 headers={"X-API-Key": "sal_your_api_key"})

if r.ok:
    data = r.json()
else:
    error = r.json()["error"]
    if error in ("ad_not_found", "page_not_found"):
        ...  # nothing to retry
    elif error == "insufficient_credits":
        ...  # top up
    elif error in ("rate_limit_exceeded", "insufficient_credits_retry_later"):
        time.sleep(int(r.headers["Retry-After"]))

2. Retry with exponential backoff

For 429 honour Retry-After; for 500, 503 and 504 wait 1 s, 2 s, 4 s… between attempts. Never retry 400, 401, 404 or 410 unchanged.

Python
import time

def fetch_with_retry(url, params, headers, max_retries=4):
    for attempt in range(max_retries):
        r = requests.get(url, params=params, headers=headers, timeout=60)
        if r.ok:
            return r.json()
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", 5)))
        elif r.status_code in (500, 503, 504):
            time.sleep(2 ** attempt)
        else:
            r.raise_for_status()
    raise RuntimeError("Gave up after retries")

3. Log the full error

Log the status, the error code, the message and the details: they are all you need to debug, and all support needs to help you.

Need Help?