Thursday, March 17, 2016

Sample code to pull Facebook Marketing account insights
#Add to header of your file
# You can find a list of all metrics mapping in http://supermetrics.com/api/getFields?ds=FA&fieldType=met
# You can find a list of all dimensions mapping in http://supermetrics.com/api/getFields?ds=FA&fieldType=dim
from facebookads.api import FacebookAdsApi
from facebookads import objects
from facebookads.objects import (
AdUser,
Campaign,
Insights,
)
import json
import os
import pprint
import time
import numbers
import csv
import copy
#Initialize a new Session and instanciate an Api object
my_app_id = '{app id}'
my_app_secret = '{app secret}'
my_access_token='{access_token}'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
me = AdUser(fbid='me')
# print all accounts
my_accounts_iterator = me.get_ad_accounts()
# choose a specific specific account
for account in my_accounts_iterator:
# print account['account_id']
if account['account_id'] == 'xxx':
my_sel_account = account
pp.pprint(my_sel_account)
header_fields = ['Date', 'Account', 'Account ID', 'Campaign name', 'Campaign ID', 'Placement', 'Device', 'Reach', 'Amount spent (USD)', 'Frequency', 'Impressions', 'Social Clicks (All)', 'Social Impressions', 'Social Reach', 'Unique Social Clicks (All)', 'Avg. Duration of Video Viewed', 'Avg. % of Video Viewed', '10-second Views', '30-second Views', 'Video Views to 100%', 'Video Views to 25%', 'Video Views to 50%', 'Video Views to 75%', 'Video Views to 95%', 'Actions', 'Checkouts Conversion Value (Conversion Pixel)', 'Key Web Page Views Conversion Value (Conversion Pixel)', 'Leads Conversion Value (Conversion Pixel)', 'Registrations Conversion Value (Conversion Pixel)', 'Check-Ins', 'Offer Claims', 'Page Likes', 'Link Clicks', 'Website Actions (All)', 'Adds to Basket (Conversion Pixel)', 'Checkouts (Conversion Pixel)', 'Add Payment Info (Facebook Pixel)', 'Add to Basket (Facebook Pixel)', 'Add to Wishlist (Facebook Pixel)', 'Complete Registration (Facebook Pixel)', 'Initiate Checkout (Facebook Pixel)', 'Lead (Facebook Pixel)', 'Purchase (Facebook Pixel)', 'Search (Facebook Pixel)', 'View Content (Facebook Pixel)', 'Key Web Page Views (Conversion Pixel)', 'Leads (Conversion Pixel)', 'Other Website Conversions (Conversion Pixel)', 'Registrations (Conversion Pixel)', 'Page Engagement', 'Photo Views', 'Post Shares', 'Post Comments', 'Post Engagement', 'Post Likes', 'Clicks to Play Video', 'Video Views']
field_dims = [Insights.Field.date_start, Insights.Field.account_name, Insights.Field.account_id, Insights.Field.campaign_name, Insights.Field.campaign_id]
field_bkdwns = [Insights.Breakdown.placement, Insights.Breakdown.impression_device]
field_mets = [Insights.Field.reach, Insights.Field.spend, Insights.Field.frequency, Insights.Field.impressions, Insights.Field.social_clicks, Insights.Field.social_impressions, Insights.Field.social_reach, Insights.Field.unique_social_clicks, Insights.Field.video_avg_sec_watched_actions, Insights.Field.video_avg_pct_watched_actions, 'video_10_sec_watched_actions', 'video_30_sec_watched_actions', Insights.Field.video_p100_watched_actions, Insights.Field.video_p25_watched_actions, Insights.Field.video_p50_watched_actions, Insights.Field.video_p75_watched_actions, Insights.Field.video_p95_watched_actions, Insights.Field.total_actions]
action_fields = ['offsite_conversion.checkout', 'offsite_conversion.key_page_view', 'offsite_conversion.lead', 'offsite_conversion.registration', 'checkin', 'receive_offer', 'like', 'link_click', 'offsite_conversion', 'offsite_conversion.add_to_cart', 'offsite_conversion.checkout', 'offsite_conversions_fb_pixel_add_payment_info', 'offsite_conversions_fb_pixel_add_to_cart', 'offsite_conversions_fb_pixel_add_to_wishlist', 'offsite_conversions_fb_pixel_complete_registration', 'offsite_conversions_fb_pixel_initiate_checkout', 'offsite_conversions_fb_pixel_lead', 'offsite_conversions_fb_pixel_purchase', 'offsite_conversions_fb_pixel_search', 'offsite_conversions_fb_pixel_view_content', 'offsite_conversion.key_page_view', 'offsite_conversion.lead', 'offsite_conversion.other', 'offsite_conversion.registration', 'page_engagement', 'photo_view', 'post', 'comment', 'post_engagement', 'post_like', 'video_play', 'video_view']
fb_fields = list(field_dims)
fb_fields.extend(field_mets)
fb_fields.append(Insights.Field.actions)
params = {
Insights.Field.unique_clicks, Insights.Field.actions],
'fields': fb_fields,
'breakdowns': field_bkdwns,
'date_preset': Insights.Preset.yesterday,
'level': Insights.Level.campaign,
}
all_rows = []
for ins in my_sel_account.get_insights(params=params):
row = []
for fl in field_dims:
row.append(str(ins.get(fl)))
for fl in field_bkdwns:
row.append(str(ins.get(fl)))
for fl in field_mets:
if isinstance(ins.get(fl,0), numbers.Number):
row.append(ins.get(fl, 0))
else:
row.append(str(ins.get(fl, 0)))
act_map = {}
for ac in ins.get('actions',{}):
act_map[ac['action_type']] = ac['value']
for afl in action_fields:
if isinstance(act_map.get(afl,0), numbers.Number):
row.append(act_map.get(afl,0))
else:
row.append(str(act_map.get(afl,0)))
all_rows.append(row)
csv_file = open('/tmp/fb.csv','wt')
try:
writer = csv.writer(csv_file, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(header_fields)
writer.writerows(all_rows)
finally:
csv_file.close()

No comments:

Post a Comment