Posts tagged with facebook-python-business-sdk

I have created this code to fetch leads from Facebook:

import pandas as pd from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.ad import Ad from facebook_business.adobjects.user import User from facebook_business.adobjects.lead import Lead import requests from datetime import datetime import time # Permanent Access Token access_token = "my_token" facebook_api = FacebookAdsApi.init(access_token=access_token) start_date = '2023-07-01'  end_date = '2023-07-31'  account_id = "my_ad_account_id" lead_fields = ['campaign_name',"created_time","field_data"] lead_params = {                 'filtering': [{'field': 'time_created', 'operator': 'GREATER_THAN', 'value': start_date},                               {'field': 'time_created', 'operator': 'LESS_THAN', 'value': end_date}                              ]               } leads_list = [] # Getting ads ad_account = AdAccount(account_id) ads = ad_account.get_ads() for ad in ads:   leads = ad.get_leads(fields=lead_fields,params=lead_params)   for lead in leads:     lead_dic = {}     lead_dic["campaign_name"] = lead["campaign_name"]     lead_dic["created_time"] = lead["created_time"]     field_data = lead["field_data"]     for field in field_data:       lead_dic[field["name"]] = field["values"][0]     leads_list.append(lead_dic) print(leads_list) 

It works for my test account that has few ads, but I get an limit error when I try to use it with my main account.

I figure that I should use batch request, but I could not make it work. Can someone please help to to adapt this code so it does not get limit errors?

I want to get Leadinfo from my Lead ads using python and the facebook API.

I have tried this:

import json from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.leadgenform import LeadgenForm from facebook_business.adobjects.lead import Lead access_token = '<my_token>' ad_account_id = 'act_my_ad_acount' FacebookAdsApi.init(access_token=access_token) ad_account = AdAccount(ad_account_id) ads = ad_account.get_ads(fields=[         Ad.Field.id,         Ad.Field.name,     ]) leads = [] for ad in ads:   lead = ad.get_leads(fields=[     Lead.Field.id,     Lead.Field.field_data     ])   leads.extend(lead) print(leads) 

However it breaks due to this error:

There have been too many calls from this ad-account. Please wait a bit and try again. 

I understand that I should be doing some kind of batch call. But I found the documentation too hard do understand. It took me three days just get the code to list the ads in my account.

Could someone, please help me?

My end goal is to retrieve the information that the users sent on the leadforms ads, ei. their name, telephone, etc..