The short answer
You can query the Facebook Ad Library API from Python with nothing but requests: confirm your identity, create a developer app, extend your token to about 60 days, then page through ads_archive with paging.next. It is free, but commercial ads only come back if they delivered in the EU, with no spend and no transcripts. For US commercial ads that are already winning, with estimated spend, transcripts and ten tags in one call, the Ad Radar Data API is the faster route, with the same Python pattern.
In this article10 sections
What this Facebook Ad Library API Python tutorial covers
This is a hands-on Facebook Ad Library API Python tutorial: get access, make a first ads_archive call with requests, page through results, survive rate limits and store everything in CSV or SQLite. Every snippet runs on Python 3.9+ with only requests installed. If you first want to know what the API can and can't return, read the Meta Ad Library API: what you can and can't get. This page assumes you have decided to use it and want working code.
The second half covers the wall you will hit if your competitors are US brands: the official API does not return US-only commercial ads, and it never returns spend or transcripts for commercial ads. That section shows the same patterns against the Ad Radar Facebook ads API, which returns all of it, already ranked.
$0
cost of the official Ad Library API
~60 days
lifetime of a long-lived user token
613
the Ad Library's rate-limit error code
2,761
ads with $50k+ estimated spend in the Ad Radar Data API
Step 1: get access and an access token
Meta's access process has not changed much, but check it against the Ad Library API page before you start (checked November 2026).
- Confirm your identity and location at facebook.com/ID, with a government ID. This is the same confirmation advertisers complete to run ads about social issues, elections or politics, and it can take a few days. Until it is approved, your calls fail even with a valid token.
- Create a Meta for Developers account at developers.facebook.com and accept the Platform Policy.
- Create an app. A plain app with no use case is enough for the Ad Library.
- Generate a user access token for that app in the Graph API Explorer. This token is short-lived: Meta's access token guide puts it at about one to two hours.
Extend the token to about 60 days
A one-hour token is fine for a test and useless for a nightly job. Exchange it for a long-lived token, as described in Meta's long-lived token guide. Run this on your machine or server, never in client code, because it uses your app secret.
import os
import requests
GRAPH_VERSION = "v27.0"
r = requests.get(
f"https://graph.facebook.com/{GRAPH_VERSION}/oauth/access_token",
params={
"grant_type": "fb_exchange_token",
"client_id": os.environ["META_APP_ID"],
"client_secret": os.environ["META_APP_SECRET"],
"fb_exchange_token": os.environ["META_SHORT_TOKEN"],
},
timeout=30,
)
r.raise_for_status()
token = r.json()
print(token["access_token"])
print("expires in", token.get("expires_in"), "seconds")
Meta says a long-lived token "generally lasts about 60 days" and warns that lifetimes can change without notice. Store it as META_AD_LIBRARY_TOKEN and put a reminder in your calendar, or handle error code 190 (invalid or expired token) by alerting yourself. v27.0 was the version selected on the ads_archive reference when we checked; bump GRAPH_VERSION as Meta releases new ones.
Step 2: your first ads_archive call with requests
The endpoint is https://graph.facebook.com/<version>/ads_archive. The parameters you will use most, from the reference:
| Parameter | Values | Note |
|---|---|---|
ad_reached_countries | JSON array of ISO codes, or ["ALL"] | Required |
search_terms | Free text, 100 characters max | Matched as keywords by default |
search_type | KEYWORD_UNORDERED, KEYWORD_EXACT_PHRASE | Default unordered |
ad_type | ALL, POLITICAL_AND_ISSUE_ADS, EMPLOYMENT_ADS, HOUSING_ADS, FINANCIAL_PRODUCTS_AND_SERVICES_ADS | Default ALL |
ad_active_status | ACTIVE, INACTIVE, ALL | Default ACTIVE |
search_page_ids | Up to 10 Page IDs | Use instead of keywords to track a brand |
fields | Comma-separated field names | Without it you get only id |
limit | Page size | Smaller pages fail less under load |
The one detail that trips people up is ad_reached_countries: it is an array, so send it JSON-encoded. Here is a complete first call for active ads mentioning "running shoes" that reached Germany:
import json
import os
import requests
GRAPH_VERSION = "v27.0"
ADS_ARCHIVE = f"https://graph.facebook.com/{GRAPH_VERSION}/ads_archive"
TOKEN = os.environ["META_AD_LIBRARY_TOKEN"]
FIELDS = ",".join([
"id", "page_id", "page_name",
"ad_creation_time", "ad_delivery_start_time", "ad_delivery_stop_time",
"ad_creative_bodies", "ad_creative_link_titles",
"ad_snapshot_url", "publisher_platforms", "languages", "eu_total_reach",
])
params = {
"access_token": TOKEN,
"search_terms": "running shoes",
"ad_reached_countries": json.dumps(["DE"]),
"ad_type": "ALL",
"ad_active_status": "ACTIVE",
"fields": FIELDS,
"limit": 100,
}
r = requests.get(ADS_ARCHIVE, params=params, timeout=60)
body = r.json()
if "error" in body:
raise SystemExit(f"{body['error']['code']}: {body['error']['message']}")
for ad in body["data"]:
text = (ad.get("ad_creative_bodies") or [""])[0]
print(ad["page_name"], ad.get("ad_delivery_start_time"), text[:80])
ad_creative_bodies and ad_creative_link_titles are arrays, one entry per card or text version, so len(ad["ad_creative_bodies"]) is a rough variant count. ad_delivery_start_time gives you days live. The fields eu_total_reach, target_locations and beneficiary_payers are filled only for ads delivered in the EU; spend and impressions only for political and issue ads (archived ad reference).
Step 3: paginate with paging.next and back off on rate limits
Results are paginated. Each response carries a paging object, and paging.next is a complete URL with your token and every parameter already in it, so you just request it until it disappears or data comes back empty.
Meta does not publish a number for the Ad Library's rate limit. The reference lists error code 613, "Calls to this api have exceeded the rate limit", and the general rate limiting guide adds codes 4 (app limit) and 17 (user limit). Errors arrive as JSON with an error object, sometimes with is_transient: true. The safe pattern is exponential backoff on those codes and an immediate stop on everything else:
import time
THROTTLE_CODES = {4, 17, 613}
class GraphError(Exception):
pass
def get_with_backoff(url, params=None, max_tries=6, first_wait=30):
wait = first_wait
for attempt in range(1, max_tries + 1):
r = requests.get(url, params=params, timeout=60)
try:
body = r.json()
except ValueError:
body = {"error": {"code": r.status_code, "message": r.text[:200], "is_transient": True}}
err = body.get("error")
if not err:
return body
retryable = (
err.get("code") in THROTTLE_CODES
or err.get("is_transient")
or r.status_code >= 500
)
if not retryable or attempt == max_tries:
raise GraphError(f"{err.get('code')}/{err.get('error_subcode')}: {err.get('message')}")
print(f"Throttled (code {err.get('code')}), sleeping {wait}s")
time.sleep(wait)
wait = min(wait * 2, 900)
def iter_ads(params, max_pages=50):
body = get_with_backoff(ADS_ARCHIVE, params)
pages = 1
while True:
data = body.get("data", [])
yield from data
next_url = body.get("paging", {}).get("next")
if not data or not next_url or pages >= max_pages:
break
body = get_with_backoff(next_url) # next_url already holds token and filters
pages += 1
ads = list(iter_ads(params, max_pages=20))
print(len(ads), "ads")
Two habits help. Don't log next_url: it contains your token. And keep max_pages low while testing, because a broad keyword with ["ALL"] countries can run for thousands of pages. A bad token fails fast with GraphError: 190/..., which is what you want in a scheduled job.
Step 4: save to CSV or SQLite
CSV is fine for a one-off look in a spreadsheet:
import csv
def save_csv(ads, path="ads.csv"):
cols = ["id", "page_name", "ad_delivery_start_time", "ad_delivery_stop_time",
"body", "title", "versions", "eu_total_reach", "ad_snapshot_url"]
with open(path, "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=cols)
w.writeheader()
for ad in ads:
bodies = ad.get("ad_creative_bodies") or []
titles = ad.get("ad_creative_link_titles") or []
w.writerow({
"id": ad["id"],
"page_name": ad.get("page_name"),
"ad_delivery_start_time": ad.get("ad_delivery_start_time"),
"ad_delivery_stop_time": ad.get("ad_delivery_stop_time"),
"body": bodies[0] if bodies else "",
"title": titles[0] if titles else "",
"versions": len(bodies),
"eu_total_reach": ad.get("eu_total_reach"),
"ad_snapshot_url": ad.get("ad_snapshot_url"),
})
For anything you run more than once, use SQLite with the ad id as the primary key and keep the raw JSON. An upsert keeps first_seen from the first pull and updates the rest, which is how you see an ad gain versions or stop:
import sqlite3
from datetime import datetime, timezone
def save_sqlite(ads, path="ad_library.db"):
con = sqlite3.connect(path)
con.execute("""
CREATE TABLE IF NOT EXISTS ads (
id TEXT PRIMARY KEY, page_id TEXT, page_name TEXT,
start_time TEXT, stop_time TEXT, versions INTEGER,
eu_total_reach INTEGER, raw TEXT, first_seen TEXT, last_seen TEXT
)""")
now = datetime.now(timezone.utc).isoformat()
rows = [(
ad["id"], ad.get("page_id"), ad.get("page_name"),
ad.get("ad_delivery_start_time"), ad.get("ad_delivery_stop_time"),
len(ad.get("ad_creative_bodies") or []), ad.get("eu_total_reach"),
json.dumps(ad), now, now,
) for ad in ads]
con.executemany("""
INSERT INTO ads VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
stop_time = excluded.stop_time,
versions = excluded.versions,
eu_total_reach = excluded.eu_total_reach,
raw = excluded.raw,
last_seen = excluded.last_seen
""", rows)
con.commit()
con.close()
save_csv(ads)
save_sqlite(ads)
The ON CONFLICT ... DO UPDATE syntax needs SQLite 3.24 or newer, which every current Python build ships.
Is there an official Python SDK or GitHub library?
Not one that does this for you. We checked both places in November 2026:
- Meta's official Python SDK, facebook-python-business-sdk (
pip install facebook-business, version 27.0.0), is built for the Marketing API. It has no class or helper forads_archive. - Meta's research team publishes the Ad-Library-API-Script-Repository on GitHub: Python scripts and a command-line tool (
fb_ads_library_api_cli.py) that page through the archive withrequests. It is useful to read, but it defaults to Graph API v14.0 and was last updated in February 2025, so pass a current version if you use it.
The endpoint is one GET with query parameters, so the 60 lines above are about as much library as you need.
What comes back for a US commercial ad
Usually nothing. Meta's ads_archive reference states the rule (checked November 2026): "Ads that did not reach any location in the EU will only return if they are about social issues, elections or politics."
So if you set ad_reached_countries to ["US"] and search for a US-only DTC brand, you get an empty data array, or only that brand's ads that also ran somewhere in the EU. Your code is not broken. The same ads are visible in the web library while they are active, which is why people end up scraping it, with the problems covered in how to use the Meta Ad Library and downloading Ad Library videos.
Even for EU-delivered commercial ads, three things are missing:
- Spend. The
spendfield exists only for political and issue ads. For commercial ads you need an estimate; the approaches are compared in estimating competitor ad spend. - Transcripts. You get the written text and an
ad_snapshot_url, not the media file and not what is said in the video. Transcribing yourself means rendering each snapshot, extracting the audio and paying for speech-to-text: OpenAI lists Whisper at $0.006 per minute and gpt-4o-mini-transcribe at $0.003 per minute on its pricing page (checked November 2026). The model is cheap; the rendering and extraction pipeline is the work. - A performance signal. Nothing tells you which ads are winning. Days live and version counts are proxies, and they mislead often, as shown in Meta Ad Library alternatives.
Getting US commercial ads, spend and transcripts in Python
If what you need is US commercial Meta ads that are already spending, the Ad Radar Facebook ads API returns them over REST with the same Python patterns. The corpus is built from the public Meta Ad Library: 2,761 Meta ads with $50k+ estimated spend, from 734 brands, Facebook and Instagram only, refreshed every day. Each ad carries spendEstimate (estimated spend in US dollars, derived from the ad's public engagement, so always an estimate), the full video transcript, tags on ten dimensions, a score and tier, days running, variants, and public poster and video URLs. The full reference is at /docs/api.
Start on the Builder plan ($299 every 4 weeks, 10,000 requests), copy your API key from Settings → API after checkout, and set it as AD_RADAR_KEY.
A small client with quota and 429 handling
Every billable response carries X-Quota-Remaining and X-RateLimit-Remaining. Over the per-minute limit or the quota, the API answers 429 with a JSON body and a Retry-After header. When the body's code is quota_exceeded, waiting will not help: the body includes an upgrade link, and there are no overage charges. Otherwise, wait and retry:
import json
import os
import sqlite3
import time
from datetime import date, timedelta
import requests
BASE = "https://app.ad-radar.dev/api/v1"
# AD_RADAR_KEY: your API key from Settings → API after checkout
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['AD_RADAR_KEY']}"
class QuotaExceeded(Exception):
pass
def call(path, params=None, max_tries=5):
for attempt in range(1, max_tries + 1):
r = session.get(f"{BASE}{path}", params=params, timeout=30)
if r.status_code == 429:
body = r.json()
if body.get("code") == "quota_exceeded":
raise QuotaExceeded(body["error"]) # message includes the upgrade link
wait = int(r.headers.get("Retry-After", "10"))
print(f"Rate limited, retrying in {wait}s")
time.sleep(wait)
continue
if r.status_code >= 500 and attempt < max_tries:
time.sleep(2 ** attempt)
continue
r.raise_for_status()
print(f"{path}: {r.headers.get('X-Quota-Remaining')} requests left")
return r.json()
raise RuntimeError(f"{path}: still failing after {max_tries} tries")
def paginate(path, params, max_pages=10):
params = dict(params)
for _ in range(max_pages):
page = call(path, params)
yield from page["data"]
if not page["pagination"]["hasMore"]:
return
params["cursor"] = page["pagination"]["nextCursor"]
Pagination is cursor-based: each response has data and pagination with limit, hasMore and nextCursor, and the cursor is only valid with the same filters. One page is one request, however many ads it holds, so use limit=100. GET /me shows your plan and remaining quota and is never counted.
Search winning video ads with transcripts
ads = list(paginate("/ads/search", {
"q": "skillet", # matches headline, body, brand and transcript
"tier": "winner",
"format": "video",
"min_spend": 100000,
"sort": "spend",
"limit": 100, # one page = one request, so take the maximum
}, max_pages=3))
for ad in ads[:10]:
hook = (ad.get("transcript") or ad.get("headline") or "")[:90]
print(f"${ad['spendEstimate']:>10,} {ad['metrics']['daysRunning']:>4}d {ad['brand']}: {hook}")
Because q also searches transcripts, you can find ads by what is said in the first seconds of the video, which the official API cannot do. Filter on tags with tags=dimension:value pairs from GET /taxonomy, for example tags=awareness:problem-aware.
Pull this week's new winners and store them
GET /winners?since= returns only the ads that entered the winner tier (top 10% by score, live 21+ days) after that date. Tiers are recomputed daily, so a weekly cron job looks like this:
def save(ads, path="winners.db"):
con = sqlite3.connect(path)
con.execute("""
CREATE TABLE IF NOT EXISTS ads (
ad_key TEXT PRIMARY KEY, brand TEXT, headline TEXT, transcript TEXT,
spend_estimate INTEGER, tier TEXT, days_running INTEGER, tags TEXT,
started_at TEXT, is_active INTEGER, raw TEXT
)""")
con.executemany("INSERT OR REPLACE INTO ads VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [(
ad["adKey"], ad["brand"], ad.get("headline"), ad.get("transcript"),
ad.get("spendEstimate"), ad["metrics"].get("tier"), ad["metrics"].get("daysRunning"),
json.dumps([f"{t['dimension']}:{t['slug']}" for t in ad.get("tags", [])]),
ad.get("startedAt"), int(bool(ad.get("isActive"))), json.dumps(ad),
) for ad in ads])
con.commit()
con.close()
since = (date.today() - timedelta(days=7)).isoformat()
try:
new_winners = list(paginate("/winners", {"since": since, "limit": 100}))
save(new_winners)
print(len(new_winners), "new winners since", since)
except QuotaExceeded as e:
print("Out of quota:", e)
The same key works on the MCP server, so Claude or ChatGPT can run these queries for you; each tool call counts as one request.
Official API vs Ad Radar Data API, side by side
| Meta Ad Library API | Ad Radar Data API | |
|---|---|---|
| Coverage | Political and issue ads worldwide; commercial ads only if delivered in the EU | 2,761 Meta ads with $50k+ estimated spend from 734 brands, US brands included |
| Which ads | Everything matching your filters, tests included | Only ads above $50k estimated spend, with winner and rising tiers |
| Spend | Ranges, political and issue ads only | Estimated spend in USD on every ad |
| Transcripts | No, snapshot URL only | Full video transcript, searchable with q |
| Tags | None | Ten dimensions: hook pattern, hook mechanism, angle, awareness, proof, format, video type, landing page type, niche, CTA type |
| Media | ad_snapshot_url | Poster and video URLs |
| Pagination | paging.next URL | Cursor, up to 100 per page |
| Rate limits | Not published; error 613 | Documented per plan; quota and rate headers on every response |
| Cost | Free, paid in setup time and missing data | Builder $299 for 10,000 requests; Scale $799 for 50,000, billed every 4 weeks |
| Time to first call | Days (identity confirmation) | Minutes (checkout, key in Settings) |
| Ranking | None: you guess from days live | Score and tier (winner, rising) on every ad |
Prices are from /api#pricing, checked November 2026. Builder lets you show the data inside your own product but not redistribute it raw; Scale adds the incremental /feed endpoint; resale and a full export are on the Reseller plan.
Which one to use
- Winning commercial Meta ads, US brands included, with spend, transcripts and tags: the Ad Radar Facebook ads API. It is the only option here that returns pre-ranked winners with estimated spend, full transcripts and ten tags in one call, and it saves you the token renewals, the empty US results and the whole transcription pipeline.
- Political, election or EU transparency research only: the official API is the first-party source for EU reach and political spend ranges.
- Both: run the official API for EU political monitoring and the Data API for the winners, writing both into the same SQLite file keyed by the Meta library ID (
libraryIdin the Data API,idinads_archive).
For any product, agent or research workflow built on ads that sell, the Data API is the shortest path from pip install requests to a list of winners. Start on Builder, or see every plan on /api#pricing. How the scores and tiers are computed is described in our methodology, and the Ad Radar winning ads library is the no-code way in.
Figures marked as estimated spend come from Ad Radar's model of engagement on public Meta Ad Library ads. They are estimates, labeled as such, and are best used to rank ads against each other. How the board is built.