'Failed to download data from facebookAds through its API
I am looking to access the Facebook ADS data to automate the download of the data and its visualization, this in order to build campaign monitoring reports and KPIs.
My main option was to use the Facebook Graph API and from Python use the token to access the data, I already have a script that shows me the accounts and campaigns but when I review the metrics and campaigns it does not extract data, my intention is to download and save the data to a CSV but it remains empty.
I don't know what the error is, could you help me?
Import facebook_business
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
from facebook_business.adobjects.adsinsights import AdsInsights
from facebook_business.adobjects.adaccountuser import AdAccountUser as AdUser
from facebook_business.api import FacebookAdsApi
access_token = 'xxxxxxx'
app_secret = 'xxxxxxx'
app_id = 'xxxxxx'
FacebookAdsApi.init(access_token=access_token)
me = AdUser(fbid='me')
my_accounts = list(me.get_ad_accounts())
for a in my_accounts: # each account
fields = ['name','objective','start_time','stop_time','effective_status']
params = {'effective_status': ['ACTIVE', 'PAUSED']}
camp = AdAccount(a['id']).get_campaigns(fields=fields,params=par
fields=[AdsInsights.Field.date_start,AdsInsights.Field.date_stop, AdsInsights.Field.reach,
AdsInsights.Field.impressions, AdsInsights.Field.spend, AdsInsights.Field.frequency,
AdsInsights.Field.clicks, AdsInsights.Field.unique_clicks, AdsInsights.Field.cpc,
AdsInsights.Field.cpm, AdsInsights.Field.ctr, AdsInsights.Field.unique_ctr,
AdsInsights.Field.cost_per_unique_click, AdsInsights.Field.website_purchase_roas,
AdsInsights.Field.account_name]
params = {'date_preset_enum': 'lifetime','time_increment':1}
filename = 'C:/Users/mlozanonon/O/BI/'+a['account_id']+'.csv'
separator = ","
# Header
header = "name,campaign_id,"
for f in fields:
header+=str(f)
header+=separator
with open(filename, 'w') as output:
output.write(header)
output.write("\n")
for c in camp: # Each campaign
insigths = c.get_insights(fields=fields,params=params)
for i in insigths: # Each campaign element
data = c['name']
data += separator
data += c['id']
data += separator
for f in fields:
if len(i) > 0: # There is data
if f in i: # Field is present
data += str(i[f])
data += separator
output.write(data)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
