How to export the response of Facebook Marketing API Ads insights to CSV.
Below are my code and the response from it.
JavaScript
x
27
27
1
from facebook_business.api import FacebookAdsApi
2
from facebook_business.adobjects.adaccount import AdAccount
3
4
app_id = 'xxxxxxxxxxxxx'
5
app_secret = 'xxxxxxxxxxxxx'
6
access_token = 'xxxxxxxxx'
7
FacebookAdsApi.init(app_id, app_secret, access_token)
8
9
params = {'time_range': {'since': '2020-01-01', 'until': '2020-12-25'},
10
'time_increment':1,
11
'level': 'adset',
12
'sort': ['spend_descending'],
13
'export_format':'csv'}
14
fields = ['account_name',
15
'campaign_name',
16
'campaign_id',
17
'adset_name',
18
'adset_id',
19
'impressions',
20
'clicks',
21
'cpm',
22
'spend',
23
'ctr']
24
25
insights = AdAccount('act_332828570147114').get_insights(params=params, fields=fields)
26
print(insights)
27
Response is
JavaScript
1
28
28
1
[<AdsInsights> {
2
"account_name": "xxx",
3
"adset_id": "xxx",
4
"adset_name": "xxx",
5
"campaign_id": "xxx",
6
"campaign_name": "xxx",
7
"clicks": "xxx",
8
"cpm": "xxx",
9
"ctr": "xxx",
10
"date_start": "xxx",
11
"date_stop": "xxx",
12
"impressions": "xxx",
13
"spend": "xxx"
14
}, <AdsInsights> {
15
"account_name": "xxx",
16
"adset_id": "xxx",
17
"adset_name": "xxx",
18
"campaign_id": "xxx",
19
"campaign_name": "xxx",
20
"clicks": "xxx",
21
"cpm": "xxx",
22
"ctr": "xxx",
23
"date_start": "xxx",
24
"date_stop": "xxx",
25
"impressions": "xxx",
26
"spend": "xxx"
27
}]
28
How can we export this response to CSV format? Any suggestion will be highly appreciated.
Advertisement
Answer
JavaScript
1
33
33
1
from facebook_business.api import FacebookAdsApi
2
from facebook_business.adobjects.adaccount import AdAccount
3
4
app_id = 'xxxxxxxxxxxxx'
5
app_secret = 'xxxxxxxxxxxxx'
6
access_token = 'xxxxxxxxx'
7
FacebookAdsApi.init(app_id, app_secret, access_token)
8
9
params = {'time_range': {'since': '2020-01-01', 'until': '2020-12-25'},
10
'time_increment':1,
11
'level': 'adset',
12
'sort': ['spend_descending'],
13
'export_format':'csv'}
14
fields = ['account_name',
15
'campaign_name',
16
'campaign_id',
17
'adset_name',
18
'adset_id',
19
'impressions',
20
'clicks',
21
'cpm',
22
'spend',
23
'ctr']
24
25
insights = list(AdAccount('act_332828570147114').get_insights(params=params, fields=fields))
26
import pandas as pd
27
28
df=pd.DataFrame(columns=fields)
29
for field in fields:
30
df["{}".format(field)]=[x['{}'.format(field)] for x in insights]
31
32
df.to_csv("insights.csv",index=False)
33
Interact with the adinsights objects as dictionaries and add them to dataframe before saving as csv!