Get leads collected by a particular lead ad form between two timestamps using Facebook Graph API

Given two unix timestamps, this Python script fetches all the leads received by a particular Facebook Lead Ads form using the Facebook v14 Graph API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import json
import requests

# Constants
ACCESS_TOKEN="YOUR_ACCESS_TOKEN"
LIMIT=500
FROM_TIMESTAMP=1678613400
UPTO_TIMESTAMP=1678704000
FORM_ID=12341241244

def create_api_url(form_id):
    return f"https://graph.facebook.com/v14.0/{form_id}/leads"

def filter_tpl(gt, lt):
    f = [
        {
            "field": "time_created",
            "operator": "GREATER_THAN",
            "value": gt
        },
        {
            "field": "time_created",
            "operator": "LESS_THAN",
            "value": lt
        }
    ]
    return json.dumps(f)

def do_query(form_id, gt, lt):
    url = create_api_url(form_id)

    querystring = {"access_token":ACCESS_TOKEN,"limit":str(LIMIT),
        "filtering":filter_tpl(gt, lt)}

    payload = ""
    response = requests.request("GET", url, data=payload, params=querystring)

    print(response.text)

if __name__ == '__main__':
    do_query(FORM_ID, FROM_TIMESTAMP, UPTO_TIMESTAMP)

Read Next

I’m running an experiment for better content recommendations. These are the 3 posts that are most likely to be interesting for you:

  • Scraping the MPB website - A Postmortem
    Unlock the secrets of data extraction with a real-world tale of triumph and trial, as you explore how overcoming challenges in web scraping can sharpen your coding skills and strategy.

  • Calculating The Number Of Digits In A Power Of 2
    Unlock the power of Python further by exploring how a simple mathematical trick can enhance your coding toolkit, especially if you enjoyed the practical application of Python in fetching data from Facebook’s API.

  • Discord Notifications from Systemd
    If you’re keen on automating tasks and notifications, learning how to send Discord alerts for your system’s service statuses could be a slick addition to your toolkit, especially after tackling Facebook API integrations.

All content is licensed under CC BY-NC-SA 4.0. Copying is an act of love - please copy!
More cool websites: Prev | Hotline Webring | Next
Built with Hugo
Theme Stack designed by Jimmy