Unable to get facebook campaigns historical data from facebook api using python

890 views Asked by At

Here is what I am trying to achieve is I want the campaigns/adsets/ads marketing spend, reach, impressions on weekly basis so that we can track our metrics on weekly basis. Like in below code snippet. I trying to fetch data from 1 June to 7 June , but in response of my request I am getting only active campaigns which is different from what I can see from facebook ads manager UI. In below code I am not getting any error but I am not getting correct data.

Is there any way we can fetch historical data for campaigns?

from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.campaign import Campaign
from facebook_business.api import FacebookAdsApi
import sys,json,os,pandas as pd,numpy as np

CONF_FILE='../conf/'+os.path.basename(sys.argv[0]).split('.')[0]+'.conf'

with open(CONF_FILE,'r',encoding='utf-8') as read_conf_file:
   read_conf=json.load(read_conf_file)

access_token = read_conf['access_token']
app_id = read_conf['app_id']
id=read_conf['ad_account_id']
FacebookAdsApi.init(access_token=access_token)

adsets=AdAccount(id).get_campaigns(fields=["name"],params={'time_range': {'since': '2020-06-01', 'until' :'2020-06-07'}})

print(adsets)
1

There are 1 answers

0
Sprizgola On

I think you are making some errors. You are trying to get the adsets via

    account.get_campaigns()

method but you will get only the campaigns. In order to fetch adsets or ads you should use this approach:

    campaigns_list = account.get_campaigns()
    adsets_list = account.get_ad_sets()
    ads_list = account.get_ads()

In this way you will able to retrieve the list of the campaigns, adsets and ads. I suggest you moreover to proceed by using a batch approach because it really help you to improve the processing time.

For what concern the the insights metrics, I suggest to fetch them via batch or in an asyncronous way like this:

    async_job = account.get_insights(fields=["insights metrics"], 
            params={"level": node, "date_range": {'since': '2020-06-01', 'until' :'2020-06-07'}, is_async=True)
    async_job.api_get()
    while async_job[AdReportRun.Field.async_percent_completion] < 100 \
         or async_job[AdReportRun.Field.async_status] != "Job Completed":
         if async_job[AdReportRun.Field.async_status] == "Job Failed":
             return None
         time.sleep(1)
         async_job.api_get()
         time.sleep(1)
    insights_list = list(async_job.get_result())

where node can be campaign, adset or ad.

It is also recommended here to use the date_preset parameter instead of date_range.

I hope I was helpful.