Search code examples
pythonfacebook-marketing-apifacebook-business-sdk

Facebook Marketing API Ads Insights to CSV in Python


How to export the response of Facebook Marketing API Ads insights to CSV.

Below are my code and the response from it.

from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount

app_id = 'xxxxxxxxxxxxx'
app_secret = 'xxxxxxxxxxxxx'
access_token = 'xxxxxxxxx'
FacebookAdsApi.init(app_id, app_secret, access_token)

params = {'time_range': {'since': '2020-01-01', 'until': '2020-12-25'},
          'time_increment':1,
          'level': 'adset',
          'sort': ['spend_descending'],
          'export_format':'csv'}
fields = ['account_name',
          'campaign_name',
          'campaign_id',
          'adset_name',
          'adset_id',
          'impressions',
          'clicks',
          'cpm',
          'spend',
          'ctr']

insights = AdAccount('act_332828570147114').get_insights(params=params, fields=fields)
print(insights)

Response is

[<AdsInsights> {
    "account_name": "xxx",
    "adset_id": "xxx",
    "adset_name": "xxx",
    "campaign_id": "xxx",
    "campaign_name": "xxx",
    "clicks": "xxx",
    "cpm": "xxx",
    "ctr": "xxx",
    "date_start": "xxx",
    "date_stop": "xxx",
    "impressions": "xxx",
    "spend": "xxx"
}, <AdsInsights> {
    "account_name": "xxx",
    "adset_id": "xxx",
    "adset_name": "xxx",
    "campaign_id": "xxx",
    "campaign_name": "xxx",
    "clicks": "xxx",
    "cpm": "xxx",
    "ctr": "xxx",
    "date_start": "xxx",
    "date_stop": "xxx",
    "impressions": "xxx",
    "spend": "xxx"
}]

How can we export this response to CSV format? Any suggestion will be highly appreciated.


Solution

  • from facebook_business.api import FacebookAdsApi
    from facebook_business.adobjects.adaccount import AdAccount
    
    app_id = 'xxxxxxxxxxxxx'
    app_secret = 'xxxxxxxxxxxxx'
    access_token = 'xxxxxxxxx'
    FacebookAdsApi.init(app_id, app_secret, access_token)
    
    params = {'time_range': {'since': '2020-01-01', 'until': '2020-12-25'},
              'time_increment':1,
              'level': 'adset',
              'sort': ['spend_descending'],
              'export_format':'csv'}
    fields = ['account_name',
              'campaign_name',
              'campaign_id',
              'adset_name',
              'adset_id',
              'impressions',
              'clicks',
              'cpm',
              'spend',
              'ctr']
    
    insights = list(AdAccount('act_332828570147114').get_insights(params=params, fields=fields))
    import pandas as pd
    
    df=pd.DataFrame(columns=fields)
    for field in fields:
        df["{}".format(field)]=[x['{}'.format(field)] for x in insights]
    
    df.to_csv("insights.csv",index=False)
    

    Interact with the adinsights objects as dictionaries and add them to dataframe before saving as csv!