adlibrary.com Logoadlibrary.com
Share

Full adlibrary API Documentation and Implementation Guide

This is a complete guide showcasing how to extract Meta Ads, Google Ads and all the others available on adlibrary.com via API. Short reminder that API access is only available to users with an active Business subscription. This is a living document and will be updated with further release changes or adaptations.

Adlibrary API Endpoint

The API endpoint is versioned, an will include the version number inside the path.

We are currently on version 1, so the endpoint is:

1https://adlibrary.com/api/v1/search

We are only expecting POST requests. Every other method will respond 405.

Adlibrary.com Authentication

The endpoint expects a Basic Authentication.
Just use your existing account's email and password, and send it base64 encoded via Authorization header.

1Authorization: Basic base64(email:password)

Business subscription required

Credits deducted (1 credit = 1 result)

Standard tier restrictions apply

Credit balance checked before search

Pricing when using the adlibrary API

Expect the same cost as with the regular GUI search, 1 result is 1 credit.

You might ask: "What if I use Google SignIn or a different OAuth provider?"
And that is an excellent question to ask. Currently that's not possible yet, but when it is, the dashboard will also get its own token management suite.

Usage and Request Body Structure / Payload

You can request the adlibrary API with following schema, using the same filters available to the frontend:

1{
2 "query": "string (required)",
3 "platforms": ["string array (optional)"],
4 "filters": {
5 "adType": "string (optional)",
6 "targetLocation": "string (optional)",
7 "dateRange": {
8 "start": "string (optional)",
9 "end": "string (optional)"
10 },
11 "exactMatch": "boolean (optional)",
12 "pageSize": "number (optional)",
13 "desiredAdvertisers": "number (optional)",
14 "limit": "number (optional)"
15 }
16}

🎯 Parameter Details

query (Required)

  • Type: string
  • Required: ✅ Yes
  • Description: Search terms to find ads
  • Min Length: 1 character
  • Max Length: No limit
  • Examples:
    json
    "query": "coffee"
    "query": "sustainable fashion brands"
    "query": "cryptocurrency trading app"
    

platforms (Optional)

  • Type: string[]

  • Required: ❌ No

  • Default: ["meta"]

  • Available Options:

    PlatformStatusDescription
    "meta"✅ ActiveFacebook/Instagram ads (real-time)
    "facebook"✅ ActiveAlias for "meta"
    "google"✅ ActiveGoogle Ads (pre-cached data)
    "twitter"🚧 in progressX/Twitter (returns empty)
    "x"🚧 in progressAlias for "twitter"
    "tiktok"🚧 in progressTikTok (returns empty)
    "linkedin"🚧 in progressLinkedin ()
  • Examples:

    json
    "platforms": ["meta"]
    "platforms": ["meta", "google"]
    "platforms": ["facebook", "google", "tiktok"]
    

🎛️ Filters Object

adType (Optional)

  • Type: string

  • Required: ❌ No

  • Default: "ALL"

  • Available Options:

    ValueDescription
    "ALL"All ad formats
    "IMAGE"Image ads only
    "VIDEO"Video ads only
    "CAROUSEL"Carousel ads only
    "TEXT"Text-based ads
  • Examples:

    json
    "adType": "ALL"
    "adType": "VIDEO"
    

targetLocation (Optional)

  • Type: string
  • Required: ❌ No
  • Default: No geographic filtering
  • Available Options:

Regions

RegionCountries Included
"DACH"Germany, Austria, Switzerland
"EU"All European Union countries
"NA"United States, Canada
"APAC"Asia Pacific region
"LATAM"Latin America

Individual Countries (ISO 2-letter codes)

json
// Major markets
"targetLocation": "US"    // United States
"targetLocation": "CA"    // Canada  
"targetLocation": "GB"    // United Kingdom
"targetLocation": "DE"    // Germany
"targetLocation": "FR"    // France
"targetLocation": "IT"    // Italy
"targetLocation": "ES"    // Spain
"targetLocation": "NL"    // Netherlands
"targetLocation": "AU"    // Australia
"targetLocation": "JP"    // Japan
"targetLocation": "BR"    // Brazil
"targetLocation": "MX"    // Mexico
"targetLocation": "IN"    // India
"targetLocation": "SG"    // Singapore

Complete Country List

Click to expand full country list

Europe: "DE", "AT", "CH", "FR", "IT", "ES", "PT", "BE", "NL", "LU", "DK", "SE", "FI", "NO", "IE", "PL", "CZ", "SK", "HU", "RO", "BG", "HR", "SI", "EE", "LV", "LT", "GR", "MT", "CY"

North America: "US", "CA"

Asia Pacific: "JP", "KR", "CN", "HK", "TW", "SG", "MY", "TH", "ID", "PH", "VN", "IN", "AU", "NZ"

Latin America: "MX", "BR", "AR", "CL", "CO", "PE", "VE", "EC", "BO", "PY", "UY"

Africa/Middle East: "ZA", "EG", "NG", "KE", "MA", "AE", "SA", "IL", "TR"

  • Examples:
    json
    "targetLocation": "DACH"
    "targetLocation": "US" 
    "targetLocation": "EU"
    

dateRange (Optional)

  • Type: object

  • Required: ❌ No

  • Default: No date filtering (all historical data)

  • Format: ISO date strings (YYYY-MM-DD)

  • Properties:

    • start (string): Start date (inclusive)
    • end (string): End date (inclusive)
  • Date Range Examples:

    json
    // Last 30 days (example dates)
    "dateRange": {
      "start": "2024-01-01",
      "end": "2024-01-31"
    }
    
    // Full year
    "dateRange": {
      "start": "2024-01-01", 
      "end": "2024-12-31"
    }
    
    // Q1 2024
    "dateRange": {
      "start": "2024-01-01",
      "end": "2024-03-31"
    }
    

exactMatch (Optional)

  • Type: boolean
  • Required: ❌ No
  • Default: false
  • Description:
    • false: Keyword matching (broader results)
    • true: Exact phrase matching (narrower, more precise results)
  • Examples:
    json
    "exactMatch": false  // "running shoes" matches "best running shoes for women"
    "exactMatch": true   // "running shoes" only matches exact phrase
    

pageSize (Optional)

  • Type: number
  • Required: ❌ No
  • Default: 50
  • Range: 1 to 1000
  • Description: Number of results per page/request
  • Examples:
    json
    "pageSize": 25   // Small batch
    "pageSize": 50   // Default
    "pageSize": 100  // Large batch  
    "pageSize": 500  // Maximum recommended
    

desiredAdvertisers (Optional)

  • Type: number
  • Required: ❌ No
  • Default: 50
  • Range: 1 to 200
  • Description: Target number of unique advertisers to find
  • Examples:
    json
    "desiredAdvertisers": 10   // Quick overview
    "desiredAdvertisers": 50   // Standard analysis
    "desiredAdvertisers": 100  // Comprehensive research
    

limit (Optional)

  • Type: number
  • Required: ❌ No
  • Default: pageSize * 10
  • Range: 1 to 1000
  • Description: Maximum total results to return
  • Examples:
    json
    "limit": 100   // Limit total results
    "limit": 500   // Large dataset
    "limit": 1000  // Maximum allowed
    

📤 Response Format

Success Response Structure

json
{
  "success": true,
  "data": {
    "ads": [/* AdData[] */],
    "advertisers": [/* AdvertiserData[] */], 
    "hasMore": false,
    "totalAds": 156,
    "totalAdvertisers": 23
  },
  "meta": {
    "query": "search terms used",
    "platforms": ["platforms searched"],
    "totalResults": 156,
    "totalAdvertisers": 23,
    "authMethod": "general_token|basic_auth",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}

AdData Object Structure

json
{
  "id": "string",                    // Unique ad identifier
  "platform": "meta|google",        // Platform where ad was found
  "page_name": "string",             // Advertiser/page name
  "ad_url": "string",                // URL to view the ad
  "titles": ["string"],              // Ad headlines/titles
  "descriptions": ["string"],        // Ad descriptions
  "captions": ["string"],            // Ad captions/CTAs  
  "reach": 45000,                    // Estimated reach (number)
  "platforms": ["facebook", "instagram"], // Platforms where ad ran
  "page_id": "string",               // Platform-specific page ID
  "spend": 3500,                     // Estimated spend (number or string)
  "website": "string",               // Landing page domain
  "target_locations": [/* array */], // Geographic targeting info
  "targetsDACH": true,               // Whether targets DACH region
  "targetedCountries": ["DE", "AT"]  // Specific countries targeted
}

AdvertiserData Object Structure

json
{
  "advertiser": "string",            // Advertiser name
  "platform": "meta|google",        // Platform
  "adCount": 15,                     // Number of ads found
  "totalReach": 45000,               // Combined reach across ads
  "totalSpend": 3500,                // Combined spend across ads
  "landingDomain": "example.com",    // Primary landing domain
  "ads": [/* AdData[] */]            // All ads from this advertiser
}

❌ Error Response Format

Error Structure

json
{
  "error": "User-friendly error message",
  "code": "ERROR_CODE_IDENTIFIER", 
  "severity": "low|medium|high|critical"
}

Complete Error Code Reference

Authentication Errors

CodeHTTPDescriptionSolution
AUTH_REQUIRED401Missing Authorization headerAdd Bearer or Basic auth
AUTH_INVALID_CREDENTIALS401Invalid token or loginVerify token/credentials

Access & Permission Errors

CodeHTTPDescriptionSolution
CREDITS_INSUFFICIENT402Not enough credits (Basic auth)Purchase more credits
API_RATE_LIMIT429Too many requestsReduce request frequency

Request Validation Errors

CodeHTTPDescriptionSolution
DATA_VALIDATION_ERROR400Invalid parametersCheck required fields
API_INVALID_REQUEST400Malformed requestValidate JSON format

Platform & System Errors

CodeHTTPDescriptionSolution
API_FACEBOOK_FAILURE500Meta/Facebook API errorTry again later
API_GOOGLE_FAILURE500Google Ads API errorTry again later
API_TIMEOUT408Search timeoutReduce scope or retry
SYSTEM_ERROR500Internal server errorContact support
SYSTEM_UNAVAILABLE503Service temporarily downTry again later

💡 Usage Patterns & Examples

Basic Search

json
{
  "query": "fitness app"
}

Multi-Platform Search

json
{
  "query": "electric vehicles",
  "platforms": ["meta", "google"]
}

Geographic Targeting

json
{
  "query": "luxury hotels", 
  "filters": {
    "targetLocation": "EU",
    "adType": "IMAGE"
  }
}

Date-Specific Research

json
{
  "query": "black friday deals",
  "filters": {
    "dateRange": {
      "start": "2024-11-01",
      "end": "2024-11-30" 
    },
    "pageSize": 100
  }
}

Competitive Analysis

json
{
  "query": "project management software",
  "platforms": ["meta", "google"],
  "filters": {
    "targetLocation": "NA",
    "desiredAdvertisers": 25,
    "limit": 500,
    "exactMatch": false
  }
}

Video Ad Focus

json
{
  "query": "online courses",
  "filters": {
    "adType": "VIDEO", 
    "targetLocation": "DACH",
    "pageSize": 50
  }
}

High-Volume Research

json
{
  "query": "cryptocurrency",
  "platforms": ["meta", "google"],
  "filters": {
    "pageSize": 200,
    "desiredAdvertisers": 100, 
    "limit": 1000,
    "targetLocation": "APAC"
  }
}

📊 Performance & Limits

Request Limits

ParameterMaximum ValueRecommendation
pageSize100050-100 for best performance
desiredAdvertisers20025-50 for typical analysis
limit1000500 for large datasets
Request timeout120 secondsN/A

Credit Usage (Basic Auth Only)

ResultsCredits DeductedExample
1-10 results1 creditSmall search
11-20 results2 creditsMedium search
21-50 results5 creditsStandard search
100 results10 creditsLarge search
500 results50 creditsResearch project

Platform Performance

PlatformResponse TimeData FreshnessReliability
Meta2-5 secondsReal-timeHigh
Google1-2 secondsPre-cached (updated daily)High
Twitter/XInstantN/A (stubbed)N/A
TikTokInstantMock dataTesting only

🔧 Integration Examples

Node.js/JavaScript

javascript
const searchAds = async (query, options = {}) => {
  const response = await fetch('https://adlibrary.com/api/v1/search', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_TOKEN',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query,
      platforms: options.platforms || ['meta'],
      filters: {
        targetLocation: options.location || 'US',
        adType: options.adType || 'ALL',
        pageSize: options.pageSize || 50,
        ...options.filters
      }
    })
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(`API Error: ${error.error} (${error.code})`);
  }
  
  return response.json();
};

// Usage
const results = await searchAds('sustainable fashion', {
  location: 'EU',
  adType: 'VIDEO',
  pageSize: 100
});

Python

python
import requests
import base64

class AdLibraryAPI:
    def __init__(self, api_token=None, email=None, password=None):
        self.base_url = 'https://adlibrary.com/api/v1'
        if api_token:
            self.headers = {
                'Authorization': f'Bearer {api_token}',
                'Content-Type': 'application/json'
            }
        elif email and password:
            credentials = base64.b64encode(f'{email}:{password}'.encode()).decode()
            self.headers = {
                'Authorization': f'Basic {credentials}',
                'Content-Type': 'application/json'
            }
    
    def search(self, query, **kwargs):
        payload = {'query': query}
        
        if 'platforms' in kwargs:
            payload['platforms'] = kwargs['platforms']
            
        filters = {}
        filter_keys = ['adType', 'targetLocation', 'dateRange', 'exactMatch', 
                      'pageSize', 'desiredAdvertisers', 'limit']
        
        for key in filter_keys:
            if key in kwargs:
                filters[key] = kwargs[key]
                
        if filters:
            payload['filters'] = filters
            
        response = requests.post(
            f'{self.base_url}/search',
            headers=self.headers,
            json=payload
        )
        
        if response.status_code != 200:
            error_data = response.json()
            raise Exception(f"API Error: {error_data['error']} ({error_data['code']})")
            
        return response.json()

# Usage
api = AdLibraryAPI(api_token='your_token_here')
results = api.search(
    'cryptocurrency trading',
    platforms=['meta', 'google'],
    targetLocation='NA',
    adType='VIDEO',
    pageSize=100
)

cURL Script

bash
#!/bin/bash

API_TOKEN="your_api_token_here"
BASE_URL="https://adlibrary.com/api/v1"

search_ads() {
    local query="$1"
    local location="${2:-US}"
    local ad_type="${3:-ALL}"
    local page_size="${4:-50}"
    
    curl -s -X POST "$BASE_URL/search" \
        -H "Authorization: Bearer $API_TOKEN" \
        -H "Content-Type: application/json" \
        -d "{
            \"query\": \"$query\",
            \"filters\": {
                \"targetLocation\": \"$location\",
                \"adType\": \"$ad_type\", 
                \"pageSize\": $page_size
            }
        }" | jq .
}

# Usage
search_ads "fitness apps" "EU" "VIDEO" 100