# Facebook Ads Library Scraper: Meta Ads, Spend & Media (`stratumics/facebook-ads-library-scraper`) Actor

Get ads from the Meta (Facebook) Ad Library by keyword, advertiser page or library link: texts, images, videos, dates, platforms and versions, plus spend for political ads. Monitor new ads.

- **URL**: https://apify.com/stratumics/facebook-ads-library-scraper.md
- **Developed by:** [Stratum ICS](https://apify.com/stratumics) (community)
- **Categories:** Social media, AI, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.40 / 1,000 ads

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

**Facebook Ads Library Scraper** gets ads from the **Meta Ad Library** (facebook.com/ads/library): every ad an advertiser runs on Facebook, Instagram, Messenger, Threads and the Audience Network, or every ad matching a keyword, with its text, images, videos, carousel cards, start date, platforms and number of versions. Political and issue ads come with **spend, impressions and the "Paid for by" disclaimer**, and ads shown in the EU can carry their **EU reach by country, age and gender**.

Use it to watch competitors' ads, collect creative inspiration, research political advertising, or feed an AI tool with ad texts. No Facebook account, cookies or API token are needed, and a monitoring mode saves only the ads that are new since your last run.

### Why use this Facebook Ads Library Scraper?

- **Every way in.** Search terms (any words or an exact phrase), advertisers by Facebook page link or page id, Ad Library links copied from your browser with all their filters, and links to single ads.
- **The whole ad.** Body text, headline, link description, button, landing page and domain, images, videos (HD and SD with preview images), carousel and catalog cards, display format and how many versions share the creative.
- **Dates as the library shows them.** Start date, end date for ads that stopped, and how many days each ad has run, a quick signal for winning creatives.
- **Political and issue ads.** Amount spent, impressions and estimated audience as ranges (with numbers you can sort on), currency and the "Paid for by" disclaimer.
- **EU transparency, on request.** Total EU reach, reach by country, age and gender, the targeted ages, gender and places, and the payer and beneficiary.
- **Monitoring.** Turn on "Only new ads" and schedule it: each run saves only ads earlier runs did not return, and the ads it checks and skips cost $0.05 per 1,000.
- **Library filters.** Country, ad category, active status, platforms, media type, ad language and the date the ads were shown.
- **Fair price.** You pay per ad saved, from $0.70 per 1,000 ads, with EU details and political data included.

### What data do you get?

| Field | Example | Notes |
|---|---|---|
| `adArchiveId`, `adLibraryUrl` | 1049062250331120 | The ad's Library ID and its link |
| `pageName`, `pageId`, `pageUrl`, `pageProfilePicture` | Dough Guy | The advertiser |
| `pageLikeCount`, `pageCategories` | 431293, Pizza | Size and category of the page |
| `isActive`, `startDate`, `endDate`, `daysRunning` | true, 2025-08-01, null, 442 | Dates as the library shows them |
| `platforms` | facebook, instagram, threads | Where the ad runs |
| `displayFormat` | VIDEO | IMAGE, VIDEO, CAROUSEL, DCO, DPA |
| `bodyText`, `title`, `linkDescription`, `caption` | No pizza oven? No problem. | The ad's texts |
| `callToAction`, `landingUrl`, `landingDomain` | Shop now, doughguy.co | Button and destination |
| `images`, `videos`, `cards` | | Media links and carousel or catalog cards |
| `versionCount`, `collationId` | 1 | Ads that share this creative and text |
| `categories` | POLITICAL | Special ad categories |
| `spend`, `impressions`, `reach`, `currency` | $350K - $400K | Political and issue ads only, as text with lower and upper numbers |
| `disclaimer` | Facebook, Inc. | "Paid for by" of political and issue ads |
| `euTransparency` | euTotalReach 46287 | With EU details on |
| `removedByMeta`, `removalReason` | false | Ads Meta took down still keep their content here |
| `containsDigitallyCreatedMedia` | false | Advertiser marked the media as digitally created or altered |
| `searchInput`, `inputType`, `scrapedAt` | election, search | Which input found the ad |

### How to scrape the Facebook Ads Library

1. Add **Search terms**, **Facebook pages** (links like facebook.com/nike or page ids) or **Ad Library links** copied from your browser.
2. Pick a **Country** (all countries by default) and any other filters: ad category, active status, platforms, media type, ad languages or dates.
3. Set **Maximum ads per input** (100 by default).
4. Press **Start**. The first 30 ads of an input arrive in a few seconds and the next 1,000 in about a minute and a half.
5. Download the results as JSON, CSV or Excel, or read them through the API.

### How much does it cost?

You pay per ad saved, and Apify bills it with your usage:

| Apify plan | Price per 1,000 ads |
|---|---|
| Free | $0.70 |
| Starter | $0.60 |
| Scale | $0.50 |
| Business | $0.40 |

So **1,000 ads cost $0.70** on the Free plan, political data and EU details included. Each run also has a start fee of $0.002. The Free plan's $5 monthly credit covers about 7,000 ads. You can set a maximum cost per run in the run options: the scraper stops at that amount and never charges past it.

With **Only new ads** on, each run still reads the advertiser's whole list, because the library has no newest-first order, and the ads it already saved before cost $0.05 per 1,000 ads checked instead of the ad price. In our test, a monitor of Nike's 300 most relevant ads saved all 300 on its first run for $0.212 (300 × $0.0007 plus the start fee); the second run found no new ads and checked the 300 for $0.017 (300 × $0.00005 plus the start fee). Run daily on an advertiser with 500 ads that adds 10 new ones a day, a monitor costs 10 × $0.0007 + 490 × $0.00005 + $0.002 = $0.034 a day, about $1 a month.

### Input

All active ads of an advertiser in the United States:

```json
{
    "pageUrls": ["https://www.facebook.com/nike"],
    "country": "US",
    "maxAdsPerInput": 20
}
```

Political ads about a topic, active and inactive, with spend and impressions:

```json
{
    "searchTerms": ["election"],
    "country": "US",
    "adCategory": "political",
    "activeStatus": "all",
    "maxAdsPerInput": 100
}
```

A daily monitor of an advertiser's new ads (schedule it, and read at least as many ads as the advertiser runs):

```json
{
    "pageUrls": ["https://www.facebook.com/nike"],
    "country": "US",
    "maxAdsPerInput": 1000,
    "onlyNewAds": true,
    "monitorName": "nike-us-daily"
}
```

Any search you set up on facebook.com/ads/library, with its filters, plus EU details:

```json
{
    "libraryUrls": ["https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=DE&media_type=all&q=nike&search_type=keyword_unordered"],
    "includeEuTransparency": true
}
```

### Output

Three real rows, trimmed: media links are shortened, and the last two rows show only some fields.

```json
[
    {
        "adArchiveId": "1049062250331120",
        "adLibraryUrl": "https://www.facebook.com/ads/library/?id=1049062250331120",
        "pageId": "714789115039964",
        "pageName": "Dough Guy",
        "pageUrl": "https://www.facebook.com/61576187677552/",
        "pageProfilePicture": "https://scontent-ord5-2.xx.fbcdn.net/.../526347582_2568423196842911_3581982555861022121_n.jpg",
        "pageLikeCount": 431293,
        "pageCategories": [
            "Food & Drink",
            "Pizza"
        ],
        "isActive": true,
        "startDate": "2025-08-01",
        "endDate": null,
        "daysRunning": 442,
        "platforms": [
            "facebook",
            "instagram",
            "audience_network",
            "messenger",
            "threads"
        ],
        "displayFormat": "VIDEO",
        "bodyText": "No pizza oven? No problem.\nThis pizza steel turns your ordinary oven into a pizza making machine.\nPerfect undercarriage, every time. Make insanely good pizza at home!\n🔥 Back in stock. Grab yours before they’re gone.",
        "title": "Turn Your Oven Into a Pizza Oven",
        "linkDescription": "Restaurant-quality pizza from your regular oven. No expensive pizza oven. No fancy equipment.",
        "caption": "doughguy.co",
        "callToAction": "Shop now",
        "callToActionType": "SHOP_NOW",
        "landingUrl": "https://doughguy.co/products/order",
        "landingDomain": "doughguy.co",
        "images": [],
        "videos": [
            {
                "hdUrl": "https://video-ord5-1.xx.fbcdn.net/.../AQN48pmsQ4Q2najnHFZtRXb83GWEeVkEw8sTiBwF9Q0M15ySl7vaXMyReuW2HKUIHgIxXPAPthmfWVvyqzZ9D1bYQYB7yZdfwMX3zYZPnJrrkQ.mp4",
                "sdUrl": "https://video-ord5-2.xx.fbcdn.net/.../AQOjlboRSV1pKzrpsB6j3a4nu2tn2m-K7savN20o9jlvo_bzV0aHmjeV8p-_61BGz4GXzhNwtIXpKt-DUXkDqfV9U_rlEIIOoQeuJaugmQ.mp4",
                "previewImageUrl": "https://scontent-ord5-2.xx.fbcdn.net/.../526582490_916089150713535_5869668450285981657_n.jpg"
            }
        ],
        "cards": [],
        "versionCount": 1,
        "collationId": "1828659051390396",
        "categories": [],
        "containsDigitallyCreatedMedia": false,
        "removedByMeta": false,
        "removalReason": null,
        "spend": null,
        "impressions": null,
        "reach": null,
        "currency": null,
        "disclaimer": null,
        "euTransparency": null,
        "searchInput": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=US&is_targeted_country=false&media_type=all&q=pizza&search_type=keyword_unordered",
        "inputType": "url",
        "scrapedAt": "2026-10-18T05:40:37.657Z"
    },
    {
        "adArchiveId": "224724862190756",
        "adLibraryUrl": "https://www.facebook.com/ads/library/?id=224724862190756",
        "pageName": "Facebook",
        "isActive": false,
        "startDate": "2020-08-13",
        "endDate": "2020-08-26",
        "daysRunning": 13,
        "platforms": [
            "facebook"
        ],
        "displayFormat": "VIDEO",
        "bodyText": "Info on how to register to vote and request mail-in ballots, track registration deadlines and more.",
        "versionCount": 1,
        "categories": [
            "POLITICAL"
        ],
        "spend": {
            "text": "$350K - $400K",
            "lower": 350000,
            "upper": 400000
        },
        "impressions": {
            "text": ">1M",
            "lower": 1000000,
            "upper": null
        },
        "reach": {
            "text": ">1M",
            "lower": 1000000,
            "upper": null
        },
        "currency": "USD",
        "disclaimer": "Facebook, Inc.",
        "searchInput": "election",
        "inputType": "search"
    },
    {
        "adArchiveId": "1550534860016399",
        "pageName": "Perfect themes",
        "startDate": "2026-05-19",
        "platforms": [
            "facebook",
            "instagram",
            "audience_network",
            "messenger",
            "threads"
        ],
        "displayFormat": "IMAGE",
        "euTransparency": {
            "euTotalReach": 46287,
            "targetAgeMin": 21,
            "targetAgeMax": 65,
            "targetGender": "All",
            "targetLocations": [
                "Guadeloupe",
                "Ireland",
                "Martinique"
            ],
            "reachByCountryAgeGender": [
                {
                    "country": "PL",
                    "ageRange": "45-54",
                    "male": 348,
                    "female": 8,
                    "unknown": 1
                },
                {
                    "country": "PL",
                    "ageRange": "65+",
                    "male": 33,
                    "female": 2,
                    "unknown": 3
                }
            ],
            "payers": [
                "北京新美互通科技有限公司"
            ],
            "beneficiaries": [
                "北京新美互通科技有限公司"
            ]
        },
        "searchInput": "nike"
    }
]
```

A `SUMMARY` record in the run's key-value store lists each input with the ads saved, the total the library reported and any error.

### Tips

- The library lists ads by relevance, not by date, so a monitor should read all of an advertiser's ads: set **Maximum ads per input** above the advertiser's ad count. The ads it checks and skips cost $0.05 per 1,000.
- Put a search term in double quotes ("running shoes") for the exact phrase.
- Ad Library links keep their own filters; the filter fields of this form apply to search terms and pages.
- Catalog and dynamic ads (DPA, DCO) store their texts per card; when the ad's own text is a placeholder such as {{product.name}}, the row shows the first card's text, as the library does.
- Media links are signed by Facebook and stop working after some days, so download images and videos you need soon after the run.
- EU details take one more request per EU ad; turn them on only when you need reach and audience data.

### Integrations

- **API**: start runs and read results over the [Apify API](https://docs.apify.com/api/v2); the API tab shows ready code.
- **Python**: `pip install apify-client`, then
  ```python
  from apify_client import ApifyClient
  client = ApifyClient("<YOUR_API_TOKEN>")
  run = client.actor("stratumics/facebook-ads-library-scraper").call(run_input={"pageUrls": ["https://www.facebook.com/nike"], "country": "US"})
  for item in client.dataset(run["defaultDatasetId"]).iterate_items():
      print(item["startDate"], item["bodyText"])
  ```
- **JavaScript**: `npm install apify-client`, then
  ```javascript
  import { ApifyClient } from 'apify-client';
  const client = new ApifyClient({ token: '<YOUR_API_TOKEN>' });
  const run = await client.actor('stratumics/facebook-ads-library-scraper').call({ searchTerms: ['running shoes'], country: 'GB', maxAdsPerInput: 200 });
  const { items } = await client.dataset(run.defaultDatasetId).listItems();
  ```
- **Zapier, Make, n8n**: use the Apify app or node to send new competitor ads to Slack, Google Sheets, Airtable or your CRM.
- **AI agents**: connect your agent to this scraper through the Apify MCP server (mcp.apify.com), so it can look up any brand's current ads on demand.
- **Webhooks and schedules**: run it daily with "Only new ads" on and get a webhook when new ads appear.

### FAQ

#### Is it legal to scrape the Meta Ad Library?

Our Actors are ethical and do not extract any private user data, such as email addresses, gender, or location. They only extract what the user has chosen to share publicly. We therefore believe that our Actors, when used for ethical purposes by Apify users, are safe. However, you should be aware that your results could contain personal data. Personal data is protected by the GDPR in the European Union and by other regulations around the world. You should not scrape personal data unless you have a legitimate reason to do so. If you're unsure whether your reason is legitimate, consult your lawyers.

The Ad Library is public by design: Meta publishes these ads so anyone can see them. Rows hold what the library shows about each ad and its advertiser page; the EU payer and beneficiary can be a person's name for small advertisers.

#### Do I need a Facebook account?

No. The scraper reads the library as a logged-out visitor, like anyone opening facebook.com/ads/library.

#### Which ads are in the library?

Ads running now on Meta's apps. Inactive ads stay in the library when they are about social issues, elections or politics (kept for seven years) or were shown in the EU (kept for a year after they last ran); other ads drop out once they stop.

#### Why do most ads have no spend or impressions?

Meta shows spend, impressions and audience size only for ads about social issues, elections or politics. For other ads shown in the EU, turn on EU details to get their reach.

#### Why does an ad's text read "This content was removed" on Facebook?

Meta took the ad down for breaking its rules and the library hides its content. Such rows have `removedByMeta` set to true with the reason, and still carry the text and media the library returned.

#### Do I need a proxy?

No setup needed. Facebook refuses the library's search pages from datacenter addresses, so the scraper loads pages over Apify datacenter proxy and the search pages after them over Apify residential proxy. Both are included in the price.

#### Where can I report a problem?

Open an issue on the Issues tab with your run link and we will look at it.

### Other tools from Stratum ICS

- [Airbnb Scraper](https://apify.com/stratumics/airbnb-scraper): Get every Airbnb listing in a city or from listing links: price per night, rating, reviews, guests, bedrooms, host and Superhost status.
- [App Store Reviews Scraper](https://apify.com/stratumics/app-store-reviews-scraper): Get Apple App Store reviews with star ratings, titles, text, app versions, helpful votes and developer replies, well past Apple's 500-review limit, for any country, plus app ratings.
- [Bilibili Scraper](https://apify.com/stratumics/bilibili-scraper): Scrape Bilibili videos by search, link or uploader without logging in: views, likes, coins, tags, uploader profiles, comments with replies and danmaku, in clean rows.
- [Facebook Posts Scraper](https://apify.com/stratumics/facebook-posts-scraper): Get posts from public Facebook pages: text, reactions by type, comments, shares, views and media, plus page details with followers, contacts, rating and creation date.
- [Google Ads Transparency Scraper](https://apify.com/stratumics/google-ads-transparency-scraper): Get the ads any advertiser runs on Google Search, YouTube, Shopping, Maps and Play, from the Ads Transparency Center: images, formats, dates, regions and EU reach.
- [Google Maps Reviews Scraper](https://apify.com/stratumics/google-maps-reviews-scraper): Get the Google Maps reviews of any place: rating, full text, exact date, photos, owner reply, reviewer details and food or service scores.
- [Google Maps Scraper](https://apify.com/stratumics/google-maps-scraper): Get the businesses on Google Maps for any search and area: name, address, phone, website, rating, review count, opening hours, plus emails and social profiles.
- [Google News Scraper](https://apify.com/stratumics/google-news-scraper): Get Google News articles with real publisher URLs (not Google redirects), source, date, image, author and optional full text.
- [Google Play Reviews Scraper](https://apify.com/stratumics/google-play-reviews-scraper): Get Google Play reviews with star ratings, text, app versions, thumbs-up counts, developer replies and feature ratings in any language, plus app details with installs and star histogram.
- [Google Trends Scraper](https://apify.com/stratumics/google-trends-scraper): Get Google Trends data as JSON, CSV or Excel: interest over time, interest by region and city, related queries, and trending searches by country.
- [Instagram Scraper](https://apify.com/stratumics/instagram-scraper): Scrape public Instagram profiles, posts, reels and comments without logging in: followers, bio, posts count, captions, likes, video views, media links, tags and music.
- [LinkedIn Jobs Scraper](https://apify.com/stratumics/linkedin-jobs-scraper): Scrape LinkedIn jobs with full descriptions, salary ranges, seniority, job type and applicant counts.
- [Reddit Scraper](https://apify.com/stratumics/reddit-scraper): Get Reddit posts and full comment threads from subreddits, searches, user profiles and post links: titles, text, scores, flair, media and replies.
- [Telegram Channel Scraper](https://apify.com/stratumics/telegram-channel-scraper): Get messages from public Telegram channels with views, dates, media, reactions, polls and forwards, plus channel info with exact subscriber counts.
- [Threads Scraper](https://apify.com/stratumics/threads-scraper): Scrape Threads profiles, posts, replies and keyword search: followers, bio, post text, likes, replies, reposts, quotes, media and links.
- [TikTok Comments Scraper](https://apify.com/stratumics/tiktok-comments-scraper): Export TikTok comments and replies from any video or photo post: text, date, likes, reply count, commenter, pinned and creator-liked flags, plus video stats.
- [TikTok Scraper](https://apify.com/stratumics/tiktok-scraper): Scrape TikTok profiles and videos: followers, likes, bio, the latest 10 to 12 videos of each profile, and full stats for any video link.
- [Website Contact Scraper](https://apify.com/stratumics/website-contact-scraper): Turn a list of websites into one row per company with verified emails, formatted phone numbers, social profiles (LinkedIn, Facebook, Instagram, X), address and contact page.
- [YouTube Scraper](https://apify.com/stratumics/youtube-scraper): Get YouTube videos from searches, channels, playlists and links with exact views, likes, comment counts, dates and tags, plus channel profiles and comments.
- [YouTube Transcript Scraper](https://apify.com/stratumics/youtube-transcript-scraper): Get YouTube transcripts and captions as plain text, timed segments, SRT or WebVTT, from video links, whole channels or playlists, in any language YouTube offers.

# Actor input Schema

## `searchTerms` (type: `array`):

Words to search the Ad Library for, one per line, as in the library's search box. Put a term in double quotes ("running shoes") to match the exact phrase.

## `searchType` (type: `string`):

Any of the words (the library's keyword search) or the exact phrase.

## `pageUrls` (type: `array`):

Advertisers to list every ad of: Facebook page links (facebook.com/nike, facebook.com/profile.php?id=...) or numeric page ids, one per line.

## `libraryUrls` (type: `array`):

Links copied from facebook.com/ads/library after setting filters there; each keeps its own search and filters (the filters below do not change them). A link to one ad (?id=...) saves that ad.

## `country` (type: `string`):

Where the ads were shown. All countries by default.

## `adCategory` (type: `string`):

All ads, or one of the library's special categories. Political and issue ads come with spend, impressions and the "Paid for by" disclaimer.

## `activeStatus` (type: `string`):

Ads running now, ads that stopped, or both.

## `platforms` (type: `array`):

Only ads shown on these platforms. Leave empty for all.

## `mediaType` (type: `string`):

Only ads with this kind of media.

## `languages` (type: `array`):

Only ads in these languages, as codes such as en, es or de. Leave empty for all.

## `dateFrom` (type: `string`):

Only ads shown on or after this date (the library's impressions date filter).

## `dateTo` (type: `string`):

Only ads shown on or before this date.

## `maxAdsPerInput` (type: `integer`):

How many ads to read for each search term, page and Ad Library link. The library lists ads by relevance, not by date.

## `includeEuTransparency` (type: `boolean`):

For ads shown in the EU, read the ad's details too: total EU reach, reach by country, age and gender, the targeted ages, gender and places, and the payer and beneficiary. Takes one more request per such ad.

## `onlyNewAds` (type: `boolean`):

Save only ads earlier runs with the same inputs have not returned. The library lists ads by relevance, so each run still reads the whole list up to the maximum below; ads it already saved before are skipped and cost $0.05 per 1,000 instead of the full ad price. The Actor remembers ad ids in the key-value store facebook-ads-library-monitor in your account. Pair it with a schedule for competitor alerts.

## `monitorName` (type: `string`):

Optional. A name for the remembered list, so different schedules keep separate histories even with the same inputs. Leave empty to derive it from the inputs.

## `maxConcurrency` (type: `integer`):

How many inputs are read at the same time. Each input's pages are read one after another.

## `proxyConfiguration` (type: `object`):

Leave Apify Proxy on: the Actor then loads library pages over Apify datacenter proxy and the search pages after them over Apify residential proxy, which Facebook requires; both are included in the price. Pick proxy groups or your own proxy URLs to send every request through them instead.

## Actor input object example

```json
{
  "searchTerms": [],
  "searchType": "keyword",
  "pageUrls": [
    "https://www.facebook.com/nike"
  ],
  "libraryUrls": [],
  "country": "US",
  "adCategory": "all",
  "activeStatus": "active",
  "platforms": [],
  "mediaType": "all",
  "languages": [],
  "maxAdsPerInput": 20,
  "includeEuTransparency": false,
  "onlyNewAds": false,
  "monitorName": "",
  "maxConcurrency": 5,
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}
```

# Actor output Schema

## `overview` (type: `string`):

No description

## `political` (type: `string`):

No description

## `summary` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "pageUrls": [
        "https://www.facebook.com/nike"
    ],
    "country": "US",
    "maxAdsPerInput": 20
};

// Run the Actor and wait for it to finish
const run = await client.actor("stratumics/facebook-ads-library-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "pageUrls": ["https://www.facebook.com/nike"],
    "country": "US",
    "maxAdsPerInput": 20,
}

# Run the Actor and wait for it to finish
run = client.actor("stratumics/facebook-ads-library-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "pageUrls": [
    "https://www.facebook.com/nike"
  ],
  "country": "US",
  "maxAdsPerInput": 20
}' |
apify call stratumics/facebook-ads-library-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,stratumics/facebook-ads-library-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/ju7FfdScRCzHbUm8l/builds/TnGjCm6zp7PdWzBtK/openapi.json
