vexqo Get an API key

Meta Ad Library API in Python: paginate and export to CSV

Search public ads, follow the cursor and save a CSV you can inspect. The downloadable script caps paid requests and keeps the response behind every page.

What this Python example collects

This guide uses Vexqo's Meta Ad Library API to search public Facebook and Instagram ads. It is a third-party API, separate from Meta's official ads_archive endpoint. You need a Vexqo key; a Meta access token will not work here.

The example searches active ads for one keyword and country, follows the returned cursor, and writes one CSV row per unique ad_archive_id. A JSON file for every page keeps the returned creative groups and collection evidence. The default run makes at most three calls of up to 30 ads each.

For political-ad research or ads covered by Meta's EU/UK archive, read the official API coverage guide first. A country filter does not create historical commercial-ad coverage where the library does not expose it.

Download and run it

Use Python 3.10 or later. The script uses Python's standard library, so there is nothing to install. Get an API key, then save it as the VEXQO_API_KEY environment variable in your terminal or secret manager. Keep the key out of the downloaded file.

Download the Python script

Terminal · after setting VEXQO_API_KEY
curl --fail --output meta_ads_to_csv.py \
  https://vexqo.dev/examples/meta_ads_to_csv.py

# Set VEXQO_API_KEY in this terminal before running.
python3 meta_ads_to_csv.py \
  --query "running shoes" \
  --country US \
  --page-size 30 \
  --max-pages 3 \
  --output-dir running-shoes-us

Choose a new output directory for each run. The script refuses to overwrite an existing export. It sends one request at a time and waits six seconds between calls, which fits the standard trial limit of ten requests per minute. Read your account limits before reducing that interval.

How Facebook Ad Library pagination works

The next cursor is at search_information.next_cursor. Send it back as cursor with the same keyword, country and filters. Treat it as an opaque value: URL-encode it, and do not split or edit it.

This is the request pattern inside the downloadable script. request_page is the helper defined in that file; it sends the key in the request header.

Python · cursor handling in the full script
parameters = {
    "q": "running shoes", "country": "US", "limit": 30,
    "active_status": "active", "view": "compact",
}
body, receipt = request_page(parameters, api_key)
cursor = body["search_information"]["next_cursor"]
if cursor:
    next_parameters = {**parameters, "cursor": cursor}
    # The full script waits, checks its page cap, and deduplicates IDs
    # before requesting the next page.

You can also follow links.next from the API with the same authentication header. This script constructs the request itself so its keyword and country stay explicit.

A source total is not an export size. total_results may be null on later pages, and upstream refusals can leave a partial result. Neither the number displayed in the library nor a missing ad in a capped export proves that every matching ad was collected.

What lands in the CSV

FileContents
ads.csvOne row per unique ad ID: advertiser, status, dates, platforms, source link and JSON columns for every returned creative group and extra assets.
page-001.json, …Each complete API response as received, its observation time, request ID when supplied and reported credit usage. The script requests the compact view.
summary.jsonFilters, page cap, pages saved, duplicate count, reported total, credit receipts, remaining cursor and the exact reason collection stopped.

creatives_json retains each returned card's text, title, destination and media together, including its source path. It does not combine unrelated cards into a made-up ad. extra_assets_json keeps extra assets separate. The full API response remains available in the page files.

Unknown values stay blank in CSV and retain their original representation in JSON. The CSV uses UTF-8 with a byte-order mark for Excel. Import ad and page IDs as Text to keep every digit. Formula-like text is prefixed with an apostrophe in CSV; the page JSON is unchanged.

Know why the export stopped

Stop reasonWhat to do
no_next_cursorThe response offered no continuation. This is the end of the observed result stream, not a guarantee of a complete historical archive.
page_capYour request cap was reached. Read has_more and next_cursor in the summary before deciding to collect more.
repeated_cursor or no_new_adsThe result stream did not advance. Inspect the saved pages before sending another paid request.
source_refused_requests or missing_cursor_with_moreTreat the export as partial. The summary and page responses retain the source information.
errorEarlier pages remain saved. HTTP 410 means the cursor expired. HTTP 429 means a rate/account limit: honor Retry-After. A timeout is not automatically retried because the server may still finish and charge.

Estimate the cost before increasing the cap

At the standard Meta search rate, each request costs one credit per ten returned ads, rounded up, with a minimum of one credit. Three requests returning 30 ads each use nine credits. Duplicate ads still count toward the API's returned results even though the CSV writes each ID once.

The example leaves paid ad-detail and product enrichment off. The compact response view itself adds no collection cost. Read GET /account for your active prices and limits, and check the response's X-Credits-Used header. The summary counts known receipts and separately reports pages whose credit header was unavailable.

See credits and errors and the live API reference for the current contract.

Choose the next step

Try a small search first

Start with one page and check the saved records against the library before increasing the cap.

Get an API key