loading...

December 3, 2026

Meta Ads Library API + Python: Auto-Export Competitor Ads to Google Sheets (2026)

Meta Ads Library API Python to Google Sheets automation workflow

Manual ad research breaks the moment you track more than 5 competitors. Instead of paying for third-party connectors every month, you can connect the free Meta Ads Library API to a simple Python script and push fresh competitor ads straight into Google Sheets on autopilot.

In this 2026 walkthrough, you’ll get the complete pipeline: exchanging a short-lived Graph Explorer token for a 60-day token, pulling active ads for a list of Page IDs, calculating ad lifespan, and writing clean rows to Google Sheets.

What You Need Before Starting

Step 1: Exchange Your Short-Lived Token for a 60-Day Token

Tokens generated in Graph API Explorer expire in ~1–2 hours. Before automating, exchange your short-lived token for a 60-day long-lived user token:

import requests

resp = requests.get(
    "https://graph.facebook.com/v21.0/oauth/access_token",
    params={
        "grant_type": "fb_exchange_token",
        "client_id": "YOUR_APP_ID",
        "client_secret": "YOUR_APP_SECRET",
        "fb_exchange_token": "SHORT_LIVED_TOKEN",
    },
    timeout=15,
)
print(resp.json()["access_token"])

Step 2: Fetch Active Ads & Calculate Ad Lifespan

The best proxy for a winning Meta ad is how long it has been running. If a brand keeps an ad active for 30, 60, or 90+ days, it is almost certainly profitable. This Python function pulls active ads for multiple Page IDs, handles pagination, and computes days_active:

import datetime as dt
import requests

def fetch_active_ads(token: str, page_ids: list[str], countries: list[str] = ["GB", "DE"]) -> list[dict]:
    url = "https://graph.facebook.com/v21.0/ads_archive"
    params = {
        "access_token": token,
        "ad_reached_countries": str(countries).replace("'", '"'),
        "search_page_ids": ",".join(page_ids),
        "ad_type": "ALL",
        "ad_active_status": "ACTIVE",
        "fields": "id,page_id,page_name,ad_delivery_start_time,publisher_platforms,ad_creative_bodies,ad_creative_link_titles,eu_total_reach,ad_snapshot_url",
        "limit": 50,
    }
    rows = []
    today = dt.date.today()

    while url:
        r = requests.get(url, params=params, timeout=20).json()
        for ad in r.get("data", []):
            start_str = ad.get("ad_delivery_start_time", "")[:10]
            days_active = (today - dt.date.fromisoformat(start_str)).days if start_str else 0
            bodies = ad.get("ad_creative_bodies") or [""]
            titles = ad.get("ad_creative_link_titles") or [""]
            rows.append([
                ad.get("page_name", ""),
                ad.get("id", ""),
                start_str,
                days_active,
                ad.get("eu_total_reach", ""),
                ",".join(ad.get("publisher_platforms", [])),
                titles[0][:120],
                bodies[0][:250],
                ad.get("ad_snapshot_url", ""),
            ])
        url = r.get("paging", {}).get("next")
        params = None  # next URL already includes query params
    return rows

Step 3: Push Clean Rows to Google Sheets

Create a Google Cloud Service Account, download its JSON key, and share your target Google Sheet with the service account email. Then append or refresh your sheet in 10 lines:

import gspread

gc = gspread.service_account(filename="service_account.json")
ws = gc.open("Competitor Meta Ads Tracker").sheet1

headers = [
    "Brand", "Library ID", "Start Date", "Days Active",
    "EU Reach", "Platforms", "Headline", "Primary Text", "Snapshot URL"
]
ads = fetch_active_ads("LONG_LIVED_TOKEN", ["15087023444", "501656423181530"])
ads.sort(key=lambda row: row[3], reverse=True)  # Longest-running winners first

ws.clear()
ws.update([headers] + ads)
print(f"Exported {len(ads)} active ads to Google Sheets.")

How to Schedule Weekly Runs for Free

  • GitHub Actions (Free): Add your script to a private repo with META_TOKEN and GOOGLE_CREDS_JSON as Secrets and run it every Monday via cron: "0 8 * * 1".
  • Local Cron / Launchd: Run python3 sync_ads.py weekly from your Mac or VPS.

Important Limitation: EU vs. Non-EU Commercial Ads

Remember that Meta’s free Ads Library API returns commercial ads (ad_type=ALL) for EU/UK/DSA regions. If your competitors only advertise in the US or Canada, combine this workflow with a Meta Ads Library scraper like Apify.

Posted in General