Select Page

First, run the following command:

pip install facebook_business

Now you can use the following snippet to fetch facebook ad performance insights from the Facebook Ads API

Python

import os
from os.path import basename
import sys
from sys import platform
import json
import time
import requests
from datetime import timedelta, date
from datetime import datetime, timedelta
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adset import AdSet
from facebook_business.adobjects.ad import Ad
from facebook_business.adobjects.adcreative import AdCreative

 

FB_CLIENT_ID = "replace_this_with_your_client_id"
FB_CLIENT_SECRET = "replace_this_with_your_client_secret"
FB_ACCESS_TOKEN = "replace_this_with_your_access_token"

 

def fetch_campaign_stats_for_date(date, account_id):
  """ 
  date: date in yyyy-mm-dd format 
  """
  
  date = date

  ad_account = AdAccount(account_id)

  fields = [
    "account_name",
    "campaign_name",
    "campaign_id",
    "adset_name",
    "adset_id",
    "ad_name",
    "ad_id",
    "impressions",
    "clicks",
    "spend",
    "actions",
    "reach"
  ]

  params = {
    "breakdowns":["device_platform"],
    "time_range": {
      "since": date,
      "until": date
    },
    "level": "ad",
    "limit": 100000
  }

  ad_performance_insights = ad_account.get_insights(fields, params)

  # do whatever you want with the statistics in JSON format
  print(ad_performance_insights) 

  return ad_performance_insights

 

if __name__ == "__main__":

  FacebookAdsApi.init(FB_CLIENT_ID, FB_CLIENT_SECRET, FB_ACCESS_TOKEN)

  facebook_account_id = "act_<your account id>"

  my_date = (datetime.now() - timedelta(1))

  fetch_campaign_stats_for_date(my_date, facebook_account_id)