# Monitoring competitor ads (Meta and Yelp)

> Pull competitors' active Meta Ad Library ads and Yelp sponsored placements on a schedule, and report what's new since the last run.

This recipe checks each competitor's active Meta ads and who is buying Yelp sponsored placements in your category, then prints what changed since the previous run.

> **Note:** Beta: the Meta and Yelp parsers were written from public documentation and haven't been checked against live responses yet.

**Cost:** $0.00018 per Meta ad and $0.00045 per Yelp result returned. 3 competitors × 50 ads plus 2 Yelp searches × 20 results is at most $0.027 + $0.018 = $0.045 a run. Searches that return nothing cost $0. Both routes cache results for 6 hours.

**You need:** Python 3.9+, `requests`, `DATAFORGAIO_API_KEY`.

```python title="competitor_ads.py"
import json
import os
import pathlib

import requests

BASE = "https://api.dataforgaio.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['DATAFORGAIO_API_KEY']}"}
STATE = pathlib.Path("ads_state.json")

COMPETITOR_PAGES = {
    # name -> Meta Ad Library URL for that advertiser's page
    "Summit Gear": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=US&view_all_page_id=111111111111111",
    "Ridgeline": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=US&view_all_page_id=222222222222222",
}
YELP_SEARCHES = {"searchTerms": ["running store"], "locations": ["Austin, TX", "Denver, CO"], "searchLimit": 20}


def call(path, payload):
    res = requests.post(f"{BASE}{path}", headers=HEADERS, json=payload, timeout=300)
    body = res.json()
    if res.status_code == 400 and "No " in body.get("error", {}).get("message", ""):
        return []  # nothing found: $0
    if res.status_code != 200:
        raise SystemExit(f"{path}: HTTP {res.status_code} {body}")
    return body


previous = json.loads(STATE.read_text()) if STATE.exists() else {"meta": {}, "yelp": []}
current = {"meta": {}, "yelp": []}

for name, url in COMPETITOR_PAGES.items():
    ads = call("/ads/meta", {"startUrls": [{"url": url}], "resultsLimit": 50, "max_cost": 0.009})
    current["meta"][name] = sorted(a["adArchiveID"] for a in ads)
    new = set(current["meta"][name]) - set(previous["meta"].get(name, []))
    print(f"{name}: {len(ads)} active ads, {len(new)} new")
    for ad in ads:
        if ad["adArchiveID"] in new:
            body = (ad["snapshot"].get("body") or {}).get("text") or ""
            print(f"  + {ad['adArchiveID']} since {ad['startDateFormatted']}: {body[:80]}")

rows = call("/ads/yelp", YELP_SEARCHES)
sponsored = sorted({f"{r['location']}|{r['name']}" for r in rows if r["isAd"]})
current["yelp"] = sponsored
for entry in sorted(set(sponsored) - set(previous["yelp"])):
    location, name = entry.split("|", 1)
    print(f"Yelp: new sponsored placement for {name} in {location}")

STATE.write_text(json.dumps(current, indent=2))
```

## Notes

- **Meta input.** `startUrls` takes Ad Library URLs (with `view_all_page_id`, `q`, `country`, `ad_type`, `active_status`) or a Facebook Page URL. `searchTerms` runs a keyword search instead. `max_cost: 0.009` caps a call at 50 ads.
- **Meta coverage.** Ads delivered in the EU, and political or issue ads anywhere, come with the Ad Library's full records (`spend`, `impressionsWithIndex`, `reachEstimate` where published). Other ads come from the first page of public Ad Library results, with fewer fields.
- **Yelp rows** include organic results too. `isAd` (also `sponsored` and `advertiser`) marks paid placements, and `position` is the order on the page.
- **"Nothing found"** comes back as HTTP 400 `invalid-input` with a "No ads found" or "No results found" message, in Apify's error shape. The helper above treats that as an empty list.
- **Receipts.** The response is a bare array, so the charge is on each item's `receipt_id` and the `X-Receipt-Id` header.
- **Freshness.** A repeat call within 6 hours may be served from cache. Send `"max_age": 0` when you need a fresh read.

Reference: [Meta Ad Library](https://dataforgaio.com/docs/api/ads-meta.md), [Yelp Search Ads](https://dataforgaio.com/docs/api/ads-yelp.md). Input and output fields are mapped in [Migrate from Apify](https://dataforgaio.com/docs/migrate-from-apify.md).
