Full adlibrary API Documentation and Implementation Guide
Complete guide to the AdLibrary API — search ads from Meta, TikTok, Google, and more programmatically. Includes authentication, endpoints, parameters, response formats, and integration examples. API access requires an active Business subscription. This is a living document and will be updated with further changes.
Sections
The adlibrary API gives you programmatic access to the same ad data you see in the app: keyword search across Facebook, Instagram, TikTok, LinkedIn, Google and YouTube, advertiser lookup, every ad of a specific brand, AI creative analysis, winners scoring, daily brand tracking and scheduled search workers. This page is the full reference, with copy-paste examples in Python, JavaScript and cURL. If you only want to use adlibrary from Claude or Cursor, skip to MCP server and agent skills.
TL;DR — Base URL
https://adlibrary.com, headerAuthorization: Bearer adl_your_key, always send your ownUser-Agent, use a 120s+ timeout. For brand research:GET /api/advertisers/search(free) → Meta page ID →POST /api/searchwithmetaPageId. For the AI review of an ad:POST /api/enrichment.
Base URL and authentication
All endpoints live under one host:
https://adlibrary.com
Use adlibrary.com exactly. www.adlibrary.com/api/... is a different service and will not accept your key.
Every request carries your API key as a Bearer token:
Authorization: Bearer adl_your_api_key
- Plan: API keys are a Business-plan feature. Team members on a Business team can create keys too (unless their admin turned API access off for them).
- Keys: create and revoke them in the app at adlibrary.com/api-access. Keys start with
adl_, the full key is shown once at creation, and you can have up to 10 keys per account. - Credits: paid calls spend credits from the same balance as the app. Paid responses report your remaining balance (
_credits.remainingon search).
Send a User-Agent header
The API sits behind Cloudflare, which rejects some default HTTP-library user agents. Python's built-in urllib gets error code 1010. Always send your own User-Agent. Any descriptive value works, e.g. YourCompany-AdPipeline/1.0.
Use generous timeouts
Searches are answered in one blocking JSON response after we merge several live ad libraries with our own index. Searches commonly take 20–60 seconds and sometimes longer (deep pages, rare keywords, title-only matching). An AI video analysis or a winners scan can take several minutes. Set your client timeout to at least 120 seconds for search and 600 seconds for /api/enrichment and winners scans. Do not fire a retry while the first request is still running: you would pay twice.
Python quick start
import requests
API_KEY = "adl_your_api_key"
BASE = "https://adlibrary.com"
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "YourCompany-AdPipeline/1.0", # required, see above
})
resp = session.post(f"{BASE}/api/search", json={
"keyword": "shampoo",
"geo": ["IND"],
"daysBack": 30,
"pageSize": 60,
}, timeout=180)
resp.raise_for_status()
data = resp.json()
print(data["total"], len(data["results"]), data["hasMore"], data["_credits"])
Credits and rate limits
| Endpoint | Cost |
|---|---|
POST /api/search | 1 credit per request (each page is a request) |
GET /api/advertisers/search, GET /api/winners/search-pages | free |
GET /api/ad-detail | free |
POST /api/enrichment (AI analysis) | 1 credit for images and videos up to 3 min, +1 per started minute beyond. Free if the ad was already analyzed |
POST /api/winners/advertiser/{pageId} | 10 credits per scan |
Brand tracking (/api/brands/..., /api/feed, /api/notifications, /api/ads/semantic) | free during the beta |
| Search workers | credits per run, see Search workers |
| Library and share links | free |
How search credits behave:
- Zero results are refunded. A search that returns no ads costs nothing.
- Errors are refunded. A
500or503response never costs a credit. - Identical repeats within 1 hour are free. Sending exactly the same request body again within an hour (retry loops, re-runs) is not charged and
_credits.usedis0. Changing anything, includingpage,pageSize,cursororsortField, is a new request and costs 1 credit.
Rate limits per API key:
| Limit | Value |
|---|---|
| All endpoints | 10,000 requests per day |
/api/search | 100 requests per minute |
/api/ad-detail | 60 requests per minute |
/api/enrichment | 20 requests per minute |
/api/winners/search-pages | 30 requests per minute |
| Winners scans | one scan at a time per user |
Over a limit you get 429 with a Retry-After header (seconds). Wait that long and retry.
Search ads
POST /api/search with a JSON body. GET /api/search with query parameters exists too, but POST is the documented interface.
What an API-key search covers: our indexed e-commerce and brand ad database, merged with live results from the Meta (Facebook and Instagram), TikTok, LinkedIn and Google (incl. YouTube) ad libraries. Results are de-duplicated across sources. For API keys the index is always the e-commerce and brand index: appType is ignored (always "3"), the gaming and mobile-app indexes are not available via the API.
curl -X POST "https://adlibrary.com/api/search" \
-H "Authorization: Bearer adl_your_key" \
-H "Content-Type: application/json" \
-H "User-Agent: YourCompany-AdPipeline/1.0" \
--max-time 180 \
-d '{
"keyword": "skincare",
"searchType": "1",
"platform": ["facebook", "instagram"],
"geo": ["IND", "GBR"],
"adsType": ["2"],
"daysBack": 30,
"pageSize": 60
}'
Keyword and text matching
keyword(string) — the search term. Live library sources only run whenkeywordis set.searchType(string) — where the keyword must appear:"0"or omitted = anywhere,"1"= title/headline,"2"= advertiser name,"4"= body/ad copy,"5"= caption,"6"= landing page URL. The restriction is enforced on every source, and pages still fill topageSizewhile more matches exist.preciseSearch(boolean) —true(default) = exact phrase, case-insensitive.false= all words, any order.excludeKeyword(string) — drop ads containing this term.
For a title-only exact match, send "searchType": "1" (with preciseSearch left at its default true). For "ads by this brand name", "searchType": "2" works, but the page-ID flow in Brand research is more complete.
Date and sort
daysBack(number) — ads seen in the last N days:1,3,7,14,30,60,90,180or365. Without any date filter our index defaults to the last 90 days.dateFrom/dateTo(string,YYYY-MM-DD) — custom range (our index goes back about 2 years).sortField(string) —-correlation(relevance),-first_seen(newest),-last_seen(recently active),-impression,-like_count,-share_count,-comment_count,-days(longest running),-heat_degree(trending),-related_ads_count. Sorting is applied per source batch, not as one global ranking across the merged result. Re-sort locally if you need a strict global order.activeStatus(string) —"active","inactive"or"all"(default). Used by the Meta, TikTok and Google sources.
Geography and language
geo(string[]) — ISO 3166-1 alpha-3 country codes:["IND"],["USA", "GBR", "DEU"]. All countries Meta supports (247) are accepted.excludeGeo(string[]) — exclude countries (applies to our index only).language(string[]) — ISO 639 language codes:"en","hi","de","fr","es","pt","ar","ja","ko","zh-CN","zh-TW"and more.
Note the format: /api/search takes alpha-3 (IND), the advertiser and winners endpoints below take alpha-2 (IN).
Platform and placement
platform(string[]) —"facebook","instagram","tiktok","linkedin","google","youtube","twitter","pinterest","yahoo","unity_ads","admob". Omit for all.placement(string[]) —"feed","stories","reels","marketplace","video_feeds","search","instream","right_column","instant_articles","audience_network","messenger".
Creative
adsType(string[]) —"1"image,"2"video,"3"carousel,"4"collection.adsFormat(string[]) — aspect ratio:"1:1","16:9","9:16","4:5","4:3".adsSize(string) — video quality:"hd"or"sd".videoDurationBegin/videoDurationEnd(number, seconds) — video length range.callToAction(string[], first value used) —"shopping","transform"(conversions),"traffic_acquisition","potential_customer"(leads),"interaction"(engagement),"other".
E-commerce
independentWebsite(string[]) — advertiser domain, e.g.["dove.com"].ecommercePlatform(string[]) —"shopify","bigcommerce","opencart","wordpress"(WooCommerce),"magento","wix","squarespace","shop.tiktok.com".
Engagement and flags
likeBegin/likeEnd,shareBegin/shareEnd,commentBegin/commentEnd(number) — engagement ranges. Impressions, views, heat and running days can be sorted by, not filtered.newAdsFlag,originalFlag,isDynamic,codFlag,searchArbitrageFlag,viewIllegal(boolean),duplicateRemoval(boolean or1/2).
Which source supports which filter
Creative, engagement, e-commerce and flag filters are applied by our index. The live libraries have their own capabilities:
source geo excludeGeo dates (dateFrom / dateTo / daysBack)
indexed database all values yes server-side; default last 90 days, max ~2 years
Meta Ad Library all values no server-side; daysBack ignored when dateTo is set
TikTok Ad Library first value only no server-side; no window sent without a date filter
LinkedIn Ad Library all values no applied after fetch, on first/last impression dates
Google Ads all values no server-side; daysBack and dateFrom: later one wins
Pagination
Keyword searches use plain page numbers. Request page: 1, 2, 3 … with the same filters while hasMore is true. The server keeps the merged walk across sources for about 2 hours, so pages do not repeat each other. A page past the end returns empty results with hasMore: false. There is no page cap for API keys.
page(number) — starts at 1.pageSize(number) — 1–200, default 60.
Each page is a separate request and costs 1 credit. total is an estimate until the walk has seen everything; once hasMore turns false it is exact. If a data provider was down during the walk the response carries degraded: true, meaning hasMore: false may not be the complete set.
ID-based searches (metaPageId, googleAtcAdvertiserId, googleAtcDomain, tiktokAdvertiser) are cursor-paginated instead: pass the response's nextCursor back as cursor on the next request. See Brand research.
Response
{
"results": [
{
"ad_key": "meta_1611336287186439",
"platform": "instagram",
"ads_type": 2,
"advertiser_name": "Brand Name",
"page_name": "Brand Page",
"page_id": "123456789",
"title": "Ad headline text",
"body": "Ad body copy...",
"message": "Main ad text",
"caption": "Caption text",
"button_text": "Shop Now",
"call_to_action": "Shop now",
"like_count": 1250,
"comment_count": 89,
"share_count": 340,
"view_count": 50000,
"impression": 120000,
"first_seen": 1719849600,
"last_seen": 1720454400,
"days_count": 7,
"heat": 850,
"preview_img_url": "https://adlibrary.com/api/media?u=...",
"video_url": "https://adlibrary.com/api/media?u=...",
"video_duration": 30,
"geo": ["IND", "GBR"],
"fb_merge_channel": ["feed", "stories"],
"landing_page_url": "https://example.com/product",
"ad_library_url": "https://www.facebook.com/ads/library/?id=1611336287186439",
"ecommerce_platform": "shopify",
"independent_website": "example.com",
"related_ads_count": 15
}
],
"total": 4230,
"page": 1,
"pageSize": 60,
"hasMore": true,
"_credits": { "used": 1, "remaining": 998, "autoCharged": false, "creditsAdded": 0 }
}
Dates are Unix timestamps (seconds). Fields vary by source: an ad from the Meta library carries EU reach and an ad_library_url, an ad from our index carries engagement counts. Media URLs point to adlibrary.com/api/media.
Brand research: advertiser → page ID → all ads
This is the recommended path when you research specific brands (rather than keywords). Two steps: find the brand's account IDs, then pull that account's ads.
Step 1 — find the advertiser's IDs (free)
GET /api/advertisers/search searches one brand name across Meta, Google and LinkedIn at once.
q Required. Brand / advertiser name, min 2 characters.
country Optional. ISO 3166-1 alpha-2, default US (e.g. IN).
limit Optional. 1-20 candidates per platform, default 10.
curl "https://adlibrary.com/api/advertisers/search?q=dove&country=IN" \
-H "Authorization: Bearer adl_your_key" \
-H "User-Agent: YourCompany-AdPipeline/1.0"
{
"query": "dove",
"country": "IN",
"best_match": {
"name": "Dove",
"confidence": 0.67,
"meta": { "id": "1234567890", "name": "Dove", "...": "..." },
"google": { "id": "AR01234567890123456789", "name": "...", "...": "..." },
"linkedin": null
},
"candidates": {
"meta": [ { "id": "1234567890", "name": "Dove", "logo": "...", "page_alias": "...", "category": "...", "likes": 0, "verified": true, "ig_username": "...", "ig_followers": 0 } ],
"google": [ { "id": "AR0123...", "name": "...", "legal_name": "...", "ad_count": 0 } ],
"linkedin": [ { "id": "2029", "name": "...", "advertiser_url": "...", "ad_count": 0, "is_person": false, "is_restricted": false } ]
}
}
candidates.meta[].id is the Meta page ID. best_match is set when at least two platforms agree on the same advertiser. Big brands often run several regional pages (e.g. a global page and an India page). Pick by name, verified, likes and ig_username, and keep all pages that belong to the brand.
To see which Meta pages actually run ads in a market, GET /api/winners/search-pages?q=dove&country=IN (free, 30/min) returns Meta pages with their ad_count:
{ "pages": [ { "page_id": "1234567890", "page_name": "Dove", "ad_count": 120, "verification": "BLUE_VERIFIED", "ig_username": "...", "source": "typeahead" } ] }
You can also pass a pasted Ad Library URL or a raw page ID as q.
Step 2 — fetch all ads of that page
Call POST /api/search with metaPageId instead of a keyword:
{
"metaPageId": "1234567890",
"geo": ["IND"],
"activeStatus": "active",
"directScrape": true
}
metaPageId(string) — the Meta page ID from step 1. Nokeywordneeded.geo(alpha-3) — reached countries. FordirectScrapethe first value is the country.activeStatus—"active","inactive"or"all"(default).directScrape(boolean, Business) — also read the page from the public Ad Library website. Meta's API only carries ads delivered in the EU (plus political ads), so for brands advertising outside the EU (India, US-only campaigns, …) set this on the first request. If the API part comes back empty we read the website automatically. The website part returns one batch for the firstgeocountry, so leavedirectScrapeoff when you follownextCursor.cursor—nextCursorfrom the previous response. Repeat whilehasMoreistrue. Apageabove 1 without a cursor returns an empty result.
Each request costs 1 credit. Other platforms work the same way:
| Param | Platform | Paging |
|---|---|---|
metaPageId | Facebook + Instagram | cursor = nextCursor |
googleAtcAdvertiserId (AR… id) | Google + YouTube | cursor = nextCursor |
googleAtcDomain (e.g. dove.com) | Google + YouTube, every advertiser on that domain | cursor = nextCursor |
linkedinCompanyId (numeric) | page, 25 ads per page | |
tiktokAdvertiser (exact advertiser name) | TikTok | cursor = nextCursor |
def all_page_ads(meta_page_id, geo="IND"):
"""Every active ad of one Meta page. 1 credit per request."""
ads, cursor, first = [], None, True
while True:
body = {"metaPageId": meta_page_id, "geo": [geo], "activeStatus": "active"}
if first:
body["directScrape"] = True # non-EU markets: also read the Ad Library website
if cursor:
body["cursor"] = cursor
r = session.post(f"{BASE}/api/search", json=body, timeout=180)
r.raise_for_status()
data = r.json()
ads.extend(data["results"])
cursor = data.get("nextCursor")
first = False
if not data.get("hasMore") or not cursor:
return ads
For ongoing monitoring of a fixed set of brands, follow them with brand tracking instead: we crawl them every day, keep the history and you read the result for free during the beta.
Ad detail
GET /api/ad-detail — full detail for one ad from a search result. Free, 60 requests/min.
creative_key Required. The ad's ad_key: meta_<id>, tiktok_<id>, linkedin_<id>, google_<id>, or a plain key (our index).
page_id Optional, Meta. The ad's page_id.
simgad_url Required for google_ keys: the ad's preview_img_url.
app_type Optional, our index. Default 3.
created_at Optional, our index. The ad's created_at (unix seconds).
curl "https://adlibrary.com/api/ad-detail?creative_key=meta_1611336287186439&page_id=123456789" \
-H "Authorization: Bearer adl_your_key" \
-H "User-Agent: YourCompany-AdPipeline/1.0"
{
"detail": { "...": "ad fields" },
"audience": {
"min_age": 18, "max_age": 65, "sex": "All", "total_reach": 1200000,
"age_detail": [ { "type": "25-34", "count": 0, "percent": 0 } ],
"sex_detail": [ { "type": "female", "count": 0, "percent": 0 } ],
"location_detail": [ { "code": "DE", "count": 0, "percent": 0 } ]
}
}
What detail contains depends on the source:
tiktok_ landing_page_url, countries, impressions per region, targeted age bands + genders,
estimated audience size, language, advertiser, media URLs, first_seen / last_seen
meta_ EU transparency data (ads delivered in the EU): EU reach, countries, page_id,
ad_library_url, age/gender/country breakdown. No landing_page_url.
linkedin_ body, title, call_to_action, landing_page_url, media, impressions,
first_seen / last_seen, estimated_spend (USD). No audience.
google_ text read from the rendered ad: title, body, call_to_action, display_url, sitelinks.
other full ad record from our index, plus audience when available.
audience is only present when the platform publishes a breakdown. {} means no detail is available for that ad.
AI ad analysis
POST /api/enrichment — the AI summary and review of one ad: brand, product and key message, a scene-by-scene transcription of the video, a hook / angle / audience analysis and a ready-to-use UGC replication brief. This is the same analysis as the AI panel in the app.
Send the ad object you got from /api/search (or any endpoint that returns ads) as ad. ad_key and platform are required, plus at least one media URL (video_url, image_url or preview_img_url). Passing the whole object is simplest; text fields and engagement numbers improve the analysis.
ad = data["results"][0] # an ad from /api/search
r = session.post(f"{BASE}/api/enrichment", json={"ad": ad}, timeout=600)
r.raise_for_status()
result = r.json()
print(result["enrichment"]["summary"])
print(result["creditsUsed"], result.get("cached"))
{
"enrichment": {
"summary": "**Brand:** ...\n**Product:** ...\n**Key Message:** ...",
"transcription": "### Scene 1 (0:00-0:03)\n**Visual:** ...\n**Speech:** ...",
"analysis": "## PHASE 1: HOOK FORENSICS\n...",
"ugc_script": "# 1:1 UGC VIDEO REPLICATION BRIEF\n...",
"markdown": "<all sections in one document>",
"source": "gemini"
},
"cached": false,
"creditsUsed": 1,
"balance": 998
}
- Cost: 1 credit for images and videos up to 3 minutes, +1 credit per started minute beyond (measured from the video, not from your input). Free when you or anyone else already analyzed that ad (
cached: true,creditsUsed: 0)."force": truere-runs the analysis and always charges. - Speed: often a minute or more for videos (the video is transcribed scene by scene). Use a 600s timeout. 20 requests/min.
- Errors:
400when the ad has no usable media,402when credits run out. A failed analysis is refunded.
For tracked brands, the winners endpoint (below) already returns an AI breakdown (hook, offer, CTA, visual, audience, formula) and concept tags per winning ad, without calling /api/enrichment.
Winners scan for one advertiser
POST /api/winners/advertiser/{pageId} — scans a Meta advertiser's full Ad Library, finds the proven winners (long runtime, reach, many variants), AI-tags the creative concept behind each and scores them. 10 credits per scan, refunded if the scan fails. One scan at a time per user; a scan can take several minutes.
pageId In the URL. Meta page ID (from /api/advertisers/search or /api/winners/search-pages).
country Optional. ISO alpha-2 reached country, default US (e.g. IN).
top_enrich Optional. Ads to deep-enrich, 1-300, default 100.
max_pages Optional. Ad Library pages to fetch (300 ads each), 1-30, default 20.
r = session.post(f"{BASE}/api/winners/advertiser/1234567890",
json={"country": "IN"}, timeout=900)
r.raise_for_status()
scan = r.json()
for item in scan["results"]:
print(item["score"]["tier"], item["score"]["composite"], item["ad"].get("title"))
With an API key the response is one JSON object:
{
"summary": {
"page_id": "1234567890", "page_name": "...", "country": "IN",
"total_ads": 418, "pages_fetched": 2, "truncated": false,
"enrichment": { "attempted": 100, "succeeded": 98, "errors": 0 },
"tier_counts": { "middle": 30, "winner": 5, "high_confidence_winner": 2 }, "concept_count": 37
},
"results": [
{ "ad": { "ad_key": "...", "title": "...", "...": "..." },
"score": { "tier": "high_confidence_winner", "composite": 0.87, "reasons": ["..."], "variant_count": 12, "tags": { "...": "..." } } }
],
"_credits": { "used": 10 }
}
An advertiser without ads returns 200 with empty results, a reason and used: 0.
Brand tracking (beta)
Follow a brand once and we crawl its ads every day on Meta, Google and LinkedIn, keep the history (including when each ad stopped), group ads into inferred ad sets, estimate spend and score its winners. All routes below take the same API key and are free while the beta runs. Brand IDs are UUIDs shared by everyone who follows the same brand. reach is what the platforms disclose (Meta discloses EU reach), est_spend and est_cpm are our estimates in USD.
Follow, list, unfollow
POST /api/brands follow a brand
GET /api/brands brands you follow (with new_count, active_ads, last_crawled_at)
DELETE /api/brands/{id} unfollow (the brand and its history stay)
POST /api/brands/{id}/follow { "notify": false } toggles notifications, { "follow": false } unfollows
POST /api/brands body: name (required), domain (optional) and at least one of meta_page_ids, google_advertiser_ids (AR…), linkedin_company_ids (arrays, from /api/advertisers/search). If one of the IDs already belongs to a tracked brand you join that brand (existing: true) and extra IDs become proposals. The first crawl starts in the background right away.
curl -X POST https://adlibrary.com/api/brands \
-H "Authorization: Bearer adl_your_key" \
-H "Content-Type: application/json" \
-H "User-Agent: YourCompany-AdPipeline/1.0" \
-d '{"name":"Dove","domain":"dove.com","meta_page_ids":["1234567890"],"google_advertiser_ids":["AR01234567890123456789"]}'
{
"advertiser": { "id": "b5f8472f-a714-4d44-b574-317a61c1993a", "name": "Dove", "meta_page_ids": ["1234567890"], "tracking_enabled": true, "followers": 1, "active_ads": 0, "...": "..." },
"existing": false,
"already_followed": false,
"proposed": [],
"brand": { "...": "..." }
}
Read a brand
GET /api/brands/{id}/profile?peek=1 description, similar brands, stats, top landing pages, sources
GET /api/brands/{id}/tracking insights: totals, time series, per-platform stats, targeting
granularity=day|week|month (default day), days=7-730 (default 90)
GET /api/brands/{id}/tracking/ads the brand's ads, paged (each ad + a tracking block)
status=all|active|inactive|new, since=<ISO timestamp> (required with status=new),
platform=meta|google|linkedin, format=image|video|carousel|text, region=eu|us|us_only,
from=YYYY-MM-DD, to=YYYY-MM-DD, set=<set_key>, sort=newest|reach|longest,
page (default 1), pageSize (1-96, default 48)
GET /api/brands/{id}/tracking/sets inferred ad sets with reach and est_spend_day
platform, status=active|all, sort=spend|ads|newest, page, pageSize (1-96, default 24)
GET /api/brands/{id}/winners current winners by concept, with facts, reasons,
AI breakdown (hook, offer, CTA, formula), variants, themes
GET /api/brands/{id}/report PDF report (application/pdf)
from=YYYY-MM-DD, to=YYYY-MM-DD, sections=overview,platforms,winners,overtime,audience,newads
Reading /profile counts as a visit and resets new_count. Add peek=1 for server-to-server reads. Ad sets: Meta publishes no campaign IDs, so we group ads that share account, launch day and landing page. That is the closest honest proxy for an ad set. Winners are scored from the tracked history every day and stay empty until the first daily run after you follow.
New and stopped ads
- New ads since your last check:
GET /api/brands/{id}/tracking/ads?status=new&since=2026-11-01T00:00:00Z - Stopped ads:
status=inactive. Every tracked ad hastracking.is_active,tracking.first_tracked_at,tracking.last_active_atandtracking.ended_at. - Across all followed brands:
GET /api/feed?new=1&limit=24returns the newest ads of every brand you follow, paged withcursor=<next_cursor>(passsincefrom the first page back on later pages).include_stopped=1also lists stopped ads. - Counts:
GET /api/notificationsreturns new and stopped ad counts per brand since your last visit (up to 14 days back).
{
"ads": [
{
"ad_key": "meta_1611336287186439",
"platform": "instagram",
"title": "...",
"impression": 242,
"estimated_spend": 1, "estimated_spend_currency": "USD",
"ad_library_url": "https://www.facebook.com/ads/library/?id=1611336287186439",
"tracking": {
"platform": "meta", "source_id": "1234567890", "is_active": true,
"first_tracked_at": "2026-11-01", "last_active_at": "2026-11-12", "ended_at": null,
"discovered_at": "2026-11-01T14:41:18.751815+00:00"
}
}
],
"total": 852, "page": 1, "pageSize": 48
}
Search tracked ads by meaning
GET /api/ads/semantic?q=... (Pro or Business, free during the beta) — describe an ad in plain words and get the closest tracked ads, across languages. Scope with brand=<id> or winners=1, filter with platform, angle, format, stage, lever (comma lists), page with limit (1–200, default 24) and offset.
angle problem_aware, solution_aware, social_proof, mechanism, founder_pov, ugc_testimonial, stat_drop, pattern_interrupt
format talking_head, ugc_stitch, studio, screen_record, b_roll_montage, animated_text, static_image, carousel
stage cold, warm, hot
lever social_proof, scarcity, authority, reciprocity, liking, unity, commitment
Brand accounts can be added to a shared brand via proposals: POST /api/brands/{id}/proposals with { "platform", "source_id" } or { "input": "<ad library link or id>" }, POST /api/brands/{id}/proposals/{pid}/vote, GET /api/brands/{id}/proposals.
Search workers
A worker is a saved search we run for you every day or once a week (Business plan). Each run returns only the ads it has not found before, filtered by your rules, and delivers them by email, to a signed webhook, or both. Up to 25 workers per account.
POST /api/workers create
GET /api/workers list (with last_run and totals)
GET /api/workers/{id} one worker
PATCH /api/workers/{id} change any field, or { "status": "paused" | "active" }
DELETE /api/workers/{id} delete with its runs
POST /api/workers/{id}/run run now (202 + run_id), costs one run
GET /api/workers/{id}/runs run history (limit 1-100)
GET /api/workers/runs/{runId} one run with its new ads and summary (?download=1 = ads as JSON file)
POST /api/workers/estimate cost of a worker before you create it (free)
Create body: name, keywords (1–100), optional filters (same as /api/search, e.g. {"geo": ["IND"]}), rules (keep or drop by advertiser, domain, text, CTA, URL, runtime, impressions, spend), pages (1–10 per keyword), page_size (1–200), schedule (daily or weekly + weekday 0–6), run_minute (UTC), email_enabled, email_attach_json, webhook_url, brief_enabled (AI summary + winners of the new ads), feed_enabled.
curl -X POST https://adlibrary.com/api/workers \
-H "Authorization: Bearer adl_your_key" \
-H "Content-Type: application/json" \
-H "User-Agent: YourCompany-AdPipeline/1.0" \
-d '{
"name": "Hair care India",
"keywords": ["shampoo", "hair oil", "conditioner"],
"filters": { "geo": ["IND"] },
"rules": [{ "mode": "exclude", "field": "domain", "op": "is", "values": ["amazon.in"] }],
"pages": 2,
"schedule": "daily",
"brief_enabled": true,
"webhook_url": "https://example.com/hooks/adlibrary"
}'
Cost per run: search = pages × (1 + floor(keywords / 5)) credits, plus 1 + floor(keywords / 5) for the brief when it is on and there are new ads. Failed searches are refunded. If credits run out the worker stops (status: "stopped_no_credits") and we email you.
Webhook: after each run with new ads we POST JSON (worker, run, summary, winners, ads, brief) with headers X-Adlibrary-Event: worker.run and X-Adlibrary-Signature: sha256=<HMAC-SHA256 of the raw body>, keyed with the webhook_secret returned once at creation. Verify it in Python:
import hashlib, hmac
def is_valid(raw_body: bytes, signature_header: str, secret: str) -> bool:
expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature_header or "")
Library and share links
Save ads into the same library you see in the app, organize them in folders and share them. All free.
GET /api/library/ads?folder={id}&page=1&pageSize=20 list saved ads (pageSize max 100)
POST /api/library/ads save { "ad_id", "platform", "ad_data", "folder_ids"? }
GET /api/library/ads/{entry_id} one saved ad + its folders
PATCH /api/library/ads/{entry_id} set its folders { "folder_ids": [...] }
DELETE /api/library/ads/{entry_id} remove from library
POST /api/library/ads/check which ads are saved
GET /api/library/folders?flat=true list folders
POST /api/library/folders create { "name", "parent_id"? }
PATCH /api/library/folders/{id} rename / move
DELETE /api/library/folders/{id} delete (ads move to General)
POST /api/share public link: { "type": "folder", "folderId" } or
{ "type": "ads", "ads": [...up to 15 ads] }
GET /api/share · DELETE /api/share/{id} list / revoke links
ad_data is the ad object from /api/search.
MCP server and agent skills
If you work in Claude, Cursor or another MCP client, you do not need to write API code. Our MCP server wraps this API as tools (search, advertiser lookup, brand ads, AI analysis, winners, brand tracking, workers, library). Hosted: add https://mcp.adlibrary.com/adl_your_key as a custom connector in Claude. Local (stdio): npx -y @adlibrary/mcp with ADLIBRARY_API_KEY set. Setup guide: adlibrary MCP server setup.
For coding agents (Claude Code and similar) there is a ready-made research skill with the full API reference and credit rules: ad library skills for agentic AI.
Error codes
Errors are JSON with an error message and, where useful, a code.
| Status | Meaning |
|---|---|
400 | Bad input: invalid JSON, missing required field, INVALID_PAGE (page must be a positive integer) |
401 | Missing or invalid API key |
402 | Insufficient credits (INSUFFICIENT_CREDITS, with balance and creditsRequired) |
403 | Plan or permission: API access needs Business, a team admin removed a permission, semantic search needs Pro/Business |
404 | Brand, worker or ad not found |
429 | Rate limit (RATE_LIMIT_EXCEEDED). Wait for Retry-After seconds |
500 | Search failed. Credit refunded |
503 | PROVIDERS_UNAVAILABLE, retryable: true. A data provider was temporarily down. Credit refunded, wait Retry-After (10s) and send the same request again: it resumes where it stopped |
{ "error": "Insufficient credits", "code": "INSUFFICIENT_CREDITS", "creditsRequired": 1, "balance": 0, "autoChargeEnabled": false }
{ "error": "Rate limit exceeded. Maximum 100 requests per minute.", "code": "RATE_LIMIT_EXCEEDED", "retryAfter": 45 }
{ "error": "...", "code": "PROVIDERS_UNAVAILABLE", "retryable": true }
Python example: competitor brand pipeline
A complete script for brand-level competitor research: resolve each brand to its Meta page, pull its active ads, run the AI analysis on the top ads and write everything to CSV. Uses requests (pip install requests).
"""
adlibrary API - competitor brand pipeline
1. resolve each brand to Meta page ids (free)
2. pull every active ad of those pages (1 credit per request)
3. AI-analyze the top N ads per brand (1+ credit per ad, free when cached)
4. write ads_export.csv
"""
import csv
import time
import requests
API_KEY = "adl_YOUR_API_KEY_HERE"
BASE = "https://adlibrary.com"
BRANDS = ["Dove", "Lux", "Surf Excel"]
COUNTRY_A2, COUNTRY_A3 = "IN", "IND" # advertiser search: alpha-2, /api/search geo: alpha-3
ANALYZE_TOP = 3
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "YourCompany-AdPipeline/1.0", # required: default UAs can be blocked (error 1010)
})
def call(method, path, timeout=180, **kwargs):
"""Request with handling for rate limits (429) and temporary provider outages (503)."""
for _ in range(5):
r = session.request(method, BASE + path, timeout=timeout, **kwargs)
if r.status_code in (429, 503):
time.sleep(int(r.headers.get("Retry-After", 10)))
continue
if r.status_code == 402:
raise SystemExit(f"Out of credits: {r.json()}")
r.raise_for_status()
return r.json()
r.raise_for_status()
def meta_pages(brand):
data = call("GET", "/api/advertisers/search", params={"q": brand, "country": COUNTRY_A2, "limit": 5})
best = (data.get("best_match") or {}).get("meta")
if best:
return [best]
# no cross-platform match: take exact-name Meta candidates
return [c for c in data["candidates"]["meta"] if c["name"].lower() == brand.lower()][:2]
def page_ads(page_id):
ads, cursor, first = [], None, True
while True:
body = {"metaPageId": page_id, "geo": [COUNTRY_A3], "activeStatus": "active"}
if first:
body["directScrape"] = True # non-EU market: also read the Ad Library website
if cursor:
body["cursor"] = cursor
data = call("POST", "/api/search", json=body)
ads.extend(data["results"])
cursor, first = data.get("nextCursor"), False
print(f" {len(ads)} ads, {data['_credits']['remaining']} credits left")
if not data.get("hasMore") or not cursor:
return ads
def analyze(ad):
data = call("POST", "/api/enrichment", json={"ad": ad}, timeout=600)
return data["enrichment"]["summary"]
def ts(v):
return time.strftime("%Y-%m-%d", time.gmtime(int(v))) if v else ""
rows = []
for brand in BRANDS:
print(brand)
for page in meta_pages(brand):
print(f" page {page['id']} {page['name']}")
ads = page_ads(page["id"])
ads.sort(key=lambda a: a.get("impression") or 0, reverse=True)
for i, ad in enumerate(ads):
rows.append({
"brand": brand,
"page_id": page["id"],
"ad_key": ad.get("ad_key"),
"platform": ad.get("platform"),
"title": ad.get("title") or "",
"body": ad.get("body") or ad.get("message") or "",
"cta": ad.get("call_to_action") or ad.get("button_text") or "",
"impressions": ad.get("impression") or "",
"first_seen": ts(ad.get("first_seen")),
"last_seen": ts(ad.get("last_seen")),
"landing_page": ad.get("landing_page_url") or "",
"ad_library_url": ad.get("ad_library_url") or "",
"preview_image": ad.get("preview_img_url") or "",
"ai_summary": analyze(ad) if i < ANALYZE_TOP else "",
})
with open("ads_export.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()) if rows else ["brand"])
writer.writeheader()
writer.writerows(rows)
print(f"Done: {len(rows)} ads -> ads_export.csv")
Python: keyword search with pagination
def keyword_search(keyword, max_pages=5, **filters):
"""Walk a keyword search page by page. 1 credit per page."""
ads = []
for page in range(1, max_pages + 1):
data = call("POST", "/api/search", json={"keyword": keyword, "page": page, "pageSize": 60, **filters})
ads.extend(data["results"])
if not data["hasMore"]:
break
return ads
# title-only exact match, video ads in India and the UK, last 30 days
ads = keyword_search("anti dandruff", searchType="1", geo=["IND", "GBR"], adsType=["2"], daysBack=30)
JavaScript example
Search a list of terms and export the ads to CSV. No dependencies (Node.js 18+).
/**
* AdLibrary API — Quick Start (Node.js)
*
* Search for ads and export results to CSV.
* No dependencies required — uses built-in Node.js APIs.
*
* Usage:
* node adlibrary-api-example.js
*/
const fs = require("fs");
// ── Configuration ───────────────────────────────────────────────────────────
const API_KEY = "adl_YOUR_API_KEY_HERE"; // Replace with your API key
const BASE_URL = "https://adlibrary.com/api/search";
const OUTPUT_FILE = "ads_export.csv";
// ── Search & Export ─────────────────────────────────────────────────────────
const CATEGORIES = {
Appliances: ["kitchen appliances", "Dyson", "KitchenAid", "Whirlpool"],
Automotive: ["car accessories", "auto parts", "AutoZone", "Tesla"],
"Arts & Crafts": ["art supplies", "craft supplies", "Cricut", "Canva"],
"Baby Products": ["baby gear", "baby stroller", "Graco", "Pampers"],
Beauty: ["skincare", "makeup", "Sephora", "The Ordinary", "Glossier"],
Books: ["books online", "audiobooks", "Kindle", "Audible"],
"Phones & Accessories": ["phone case", "smartphone", "Samsung Galaxy", "iPhone accessories"],
"Clothing & Fashion": ["fashion", "clothing brand", "Shein", "Zara", "Nike apparel"],
Music: ["headphones", "music streaming", "Spotify", "Bose"],
"Office Supplies": ["office supplies", "desk accessories", "Staples", "HP printer"],
Electronics: ["electronics", "laptop", "Sony", "Apple", "Samsung"],
"Home & Kitchen": ["home decor", "kitchen gadgets", "IKEA", "Instant Pot"],
"Health & Wellness": ["supplements", "vitamins", "fitness", "Athletic Greens"],
"Lawn & Garden": ["garden tools", "outdoor furniture", "lawn care", "Husqvarna"],
"Pet Supplies": ["dog food", "pet supplies", "Chewy", "BarkBox"],
"Sports & Outdoors": ["sports equipment", "running shoes", "Nike", "Adidas"],
"Toys & Games": ["toys", "board games", "LEGO", "Hasbro"],
"Video Games": ["video games", "gaming", "PlayStation", "Xbox", "Nintendo"],
};
const AD_TYPES = { 1: "Image", 2: "Video", 3: "Carousel", 4: "Collection" };
const CSV_FIELDS = [
"category", "search_term", "advertiser_name", "platform", "ad_type",
"title", "body", "call_to_action", "impressions", "like_count",
"comment_count", "share_count", "days_running", "first_seen",
"last_seen", "landing_page", "preview_image", "ad_key",
];
function tsToDate(ts) {
if (!ts) return "";
try { return new Date(ts * 1000).toISOString().slice(0, 10); }
catch { return ""; }
}
function escapeCsv(val) {
const s = String(val ?? "");
if (s.includes(",") || s.includes('"') || s.includes("\n")) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
}
function adToRow(ad, category, searchTerm) {
return {
category,
search_term: searchTerm,
advertiser_name: ad.advertiser_name || "",
platform: ad.platform || "",
ad_type: AD_TYPES[ad.ads_type] || String(ad.ads_type || ""),
title: ad.title || "",
body: ad.body || ad.message || "",
call_to_action: ad.call_to_action || ad.button_text || "",
impressions: ad.impression || ad.all_exposure_value || "",
like_count: ad.like_count ?? "",
comment_count: ad.comment_count ?? "",
share_count: ad.share_count ?? "",
days_running: ad.days_count ?? "",
first_seen: tsToDate(ad.first_seen),
last_seen: tsToDate(ad.last_seen),
landing_page: ad.landing_page_url || ad.store_url || "",
preview_image: ad.preview_img_url || "",
ad_key: ad.ad_key || "",
};
}
async function searchAds(keyword, page = 1) {
const res = await fetch(BASE_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent": "AdLibrary-API-Client/1.0",
},
body: JSON.stringify({ keyword, appType: "3", page, pageSize: 60 }),
});
if (res.status === 402) {
const err = await res.json();
console.log(` ✗ Out of credits. Balance: ${err.balance ?? "?"}`);
return null;
}
if (res.status === 429) {
const wait = parseInt(res.headers.get("Retry-After") || "10");
console.log(` ⏳ Rate limited. Waiting ${wait}s...`);
await new Promise((r) => setTimeout(r, wait * 1000));
return searchAds(keyword, page);
}
if (!res.ok) {
const err = await res.json().catch(() => ({}));
console.log(` ✗ Error ${res.status}: ${err.error || "Unknown error"}`);
return [];
}
const data = await res.json();
const results = data.results || [];
const remaining = data._credits?.remaining ?? "?";
console.log(` ✓ ${results.length} ads — ${remaining} credits remaining`);
return results;
}
async function main() {
if (API_KEY === "adl_YOUR_API_KEY_HERE") {
console.error("ERROR: Please set your API key in the script (API_KEY variable).");
process.exit(1);
}
const allRows = [];
let creditsUsed = 0;
console.log(`AdLibrary Ad Research — ${Object.keys(CATEGORIES).length} categories\n`);
for (const [category, terms] of Object.entries(CATEGORIES)) {
console.log(`📁 ${category}`);
for (const term of terms) {
process.stdout.write(` Searching: "${term}"... `);
const results = await searchAds(term);
if (results === null) {
console.log("\nStopping: no credits remaining.");
break;
}
for (const ad of results) {
allRows.push(adToRow(ad, category, term));
}
creditsUsed++;
await new Promise((r) => setTimeout(r, 1000));
}
}
// Deduplicate
const seen = new Set();
const unique = allRows.filter((row) => {
if (seen.has(row.ad_key)) return false;
seen.add(row.ad_key);
return true;
});
// Write CSV
const header = CSV_FIELDS.join(",");
const lines = unique.map((row) =>
CSV_FIELDS.map((f) => escapeCsv(row[f])).join(",")
);
fs.writeFileSync(OUTPUT_FILE, [header, ...lines].join("\n"), "utf-8");
console.log(`\nDone! ${unique.length} unique ads exported to ${OUTPUT_FILE}`);
console.log(` Total fetched: ${allRows.length}, Dupes removed: ${allRows.length - unique.length}`);
console.log(` Credits used: ~${creditsUsed}`);
}
main().catch(console.error);
Shell example
#!/bin/bash
#
# AdLibrary API — Quick Start (Shell/cURL)
#
# Search for ads and save the raw JSON response.
# Each request costs 1 credit and returns up to 60 ads.
#
# Usage:
# chmod +x adlibrary-api-example.sh
# ./adlibrary-api-example.sh
API_KEY="adl_YOUR_API_KEY_HERE" # Replace with your API key
BASE_URL="https://adlibrary.com/api/search"
# ── Single search ────────────────────────────────────────────────────────────
# Search for "Nike" ads and save the full JSON response
echo "Searching for 'Nike' ads..."
curl -s -X POST "$BASE_URL" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "User-Agent: AdLibrary-API-Client/1.0" \
-d '{"keyword":"Nike","appType":"3"}' \
-o nike_ads.json
echo " ✓ Saved to nike_ads.json"
# ── Pagination ───────────────────────────────────────────────────────────────
# Fetch page 2 of results (costs 1 additional credit)
# curl -s -X POST "$BASE_URL" \
# -H "Authorization: Bearer $API_KEY" \
# -H "Content-Type: application/json" \
# -H "User-Agent: AdLibrary-API-Client/1.0" \
# -d '{"keyword":"Nike","appType":"3","page":2}' \
# -o nike_ads_page2.json
# ── Batch search ─────────────────────────────────────────────────────────────
# Search multiple keywords and save each to a separate JSON file
KEYWORDS=("skincare" "Samsung" "LEGO" "dog food" "running shoes")
echo ""
echo "Batch searching ${#KEYWORDS[@]} keywords..."
for keyword in "${KEYWORDS[@]}"; do
filename="${keyword// /_}_ads.json"
printf " Searching: %-20s" "\"$keyword\"..."
HTTP_CODE=$(curl -s -o "$filename" -w "%{http_code}" \
-X POST "$BASE_URL" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "User-Agent: AdLibrary-API-Client/1.0" \
-d "{\"keyword\":\"$keyword\",\"appType\":\"3\"}")
if [ "$HTTP_CODE" = "200" ]; then
echo " ✓ → $filename"
elif [ "$HTTP_CODE" = "402" ]; then
echo " ✗ Out of credits"
rm -f "$filename"
break
elif [ "$HTTP_CODE" = "429" ]; then
echo " ⏳ Rate limited, waiting 10s..."
rm -f "$filename"
sleep 10
else
echo " ✗ Error $HTTP_CODE"
rm -f "$filename"
fi
sleep 1
done
echo ""
echo "Done! JSON files saved in current directory."
Further Reading
Related Articles

Cross-Platform AI Marketing Tool AdLibrary.com Launches With Over 1 Billion Ads
The first tool to search ads across Facebook, Instagram, TikTok, Google, YouTube, Twitter (X), Pinterest and more — all in one place.
Strategic Facebook Ads Management: A Comprehensive Guide for 2026
Master Facebook ads management with structured workflows for creative research, campaign setup, optimization, and scaling. The complete 2026 practitioner's guide.