Skip to content

Instantly share code, notes, and snippets.

@alecbw
Last active July 12, 2023 18:50
Show Gist options
  • Save alecbw/2c3e5fa2ed223f5085069c2ae6e5c8bd to your computer and use it in GitHub Desktop.
Save alecbw/2c3e5fa2ed223f5085069c2ae6e5c8bd to your computer and use it in GitHub Desktop.
A quick dump of Facebook Performance data on a given date or date range. This will fail if your data is too large
import os
import requests
def construct_api_call(date_tuple, structure_level, time_level):
url = f"https://graph.facebook.com/v10.0/{os.environ['FB_ACCOUNT_ID']}/insights"
url += "?action_attribution_windows=['7d_click','1d_view']"
url += f"&time_range[since]={date_tuple[0]}"
url += f"&time_range[until]={date_tuple[1]}"
url += "&time_increment=1"
url += f"&limit={limit}"
url += f'&filtering=[{"field":"{structure_level}.effective_status","operator":"IN","value":["ACTIVE","PAUSED","DELETED","PENDING_REVIEW","DISAPPROVED","PREAPPROVED","PENDING_BILLING_INFO","CAMPAIGN_PAUSED","ARCHIVED","ADSET_PAUSED","WITH_ISSUES"]}]'
url += "&fields=ad_name,adset_name,campaign_name,ad_id,adset_id,campaign_id,actions,clicks,objective,date_start,date_stop,impressions,spend,inline_link_clicks,inline_post_engagement"
if time_level == "daily":
url += ",video_avg_time_watched_actions,video_p100_watched_actions,video_p25_watched_actions,video_p50_watched_actions,video_p75_watched_actions,video_p95_watched_actions,video_play_actions,video_play_curve_actions,video_30_sec_watched_actions,video_thruplay_watched_actions"
elif time_level == "hourly":
url += "&breakdowns=hourly_stats_aggregated_by_advertiser_time_zone"
return url
def make_api_call(url):
headers = {"Authorization": "Bearer " + os.environ["FB_ACCESS_TOKEN"]}
resp = requests.get(url, headers=headers)
return resp
def unpack_result_actions(data):
action_types = [
"video_view",
"landing_page_view",
"post_reaction",
"post",
"comment",
"link_click",
"offsite_conversion.fb_pixel_purchase",
"offsite_conversion.fb_pixel_initiate_checkout"
]
if (type(data) == type(None) or (not data.get("actions")) or len(data.get("actions")) == 0):
return data
actions = data.get("actions")
for action in actions:
action_type = action["action_type"]
if action_type in action_types:
db_col_name = action_type[action_type.find(".") + 1 :]
data[db_col_name] = int(action.get("1d_view", 0)) + int(action.get("7d_click", 0))
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment