Skip to Content

How to extract Facebook ads data using Python?

How to extract Facebook ads data using Python?

With over 2.8 billion monthly active users, Facebook is the largest social media platform in the world. Businesses big and small use Facebook ads to reach their target audience and drive results. But in order to optimize your ad campaigns, you need data.

Luckily, Facebook provides a robust ads API that allows you to extract detailed data on your ad performance. By using Python to access this API, you can pull this data into a CSV or Excel spreadsheet for analysis.

In this comprehensive guide, we’ll cover everything you need to know to extract your Facebook ads data using Python, including:

What data can you extract from the Facebook ads API?

The Facebook ads API allows you to extract a wealth of data to analyze the performance of your ad campaigns. Here are some of the key data points available:

– Campaign name, status, and budget
– Ad name, status, placement, and creative versions
– Impressions, clicks, CTR, reach, frequency
– Spend, cost per result
– Conversions, cost per conversion
– Demographic data on reach and conversions
– Broad category, detailed targeting, and interest category data
– And more!

With all this data, you can calculate metrics like CPA, ROAS, CPC, analyze the performance of different audience segments, creatives, placements etc. Having the raw data available enables detailed analysis and optimization.

Why use Python to extract Facebook ads data?

Here are some of the key benefits of using Python to access the Facebook ads API:

– Powerful data analysis capabilities with libraries like NumPy, Pandas, Matplotlib etc.
– Automate recurrent data pulls using scheduler instead of repetitive manual exports
– Flexibility to transform and analyze data however you want
– Integrate data pulls into other processes and systems
– Runs on virtually any platform including Windows, Mac, Linux cloud services
– Large open source community for support

In short, Python provides the tools to efficiently access the data you need and slice and dice it to gain insights into your ad performance.

Overview of the process

At a high level, here are the steps we’ll cover to extract your Facebook ads data using Python:

1. Install prerequisites like Python and dependencies
2. Obtain Facebook API credentials
3. Install Facebook SDK for Python
4. Write a Python script to make API calls
5. Extract data into Pandas dataframe
6. Transform and analyze data as needed
7. Output data to CSV/Excel

Next, let’s look at each of these steps in more detail.

Installing prerequisites

To follow along with this guide, you’ll need to have the following installed and set up:

– Python 3 (we recommend the latest stable version)
– Python package manager Pip
– Facebook Ads SDK for Python
– pandas, matplotlib and other libraries for data analysis (covered later)

If you don’t already have Python installed, download the latest version (3.8 or higher) from [python.org](https://www.python.org/downloads/). The installer will set up Python and pip for you.

Next, you’ll need to install the Facebook SDK for Python, which we’ll use to access the Facebook ads API. Run the following command to install it using pip:

“`
pip install facebook_business
“`

This will download and install the SDK along with any required dependencies.

With that, you now have everything needed to start accessing the Facebook ads API using Python!

Obtaining API credentials

To make API calls, you’ll need to obtain credentials like an Access Token and Ad Account ID. Here’s how to get them:

1. Go to the [Facebook Developers page](https://developers.facebook.com/) and log in with your Facebook credentials.

2. Create a new App by clicking on ‘My Apps’ > ‘Create App’. Enter a display name and contact email for the app.

3. Once created, go to the app Dashboard and click ‘Set Up’ on the Facebook Login product.

4. Under the ‘Facebook Login’ settings, click ‘Settings > Advanced’ and toggle ‘Client OAuth Login’ to YES. This enables the OAuth flow needed to generate access tokens.

5. Next, click on ‘+ Add Product’ and select ‘Marketing API’. Click ‘Set Up’ and accept the terms to enable this product for your app.

6. Under the Marketing API settings, copy and save the `app_id`, `app_secret` and `id` values. We’ll need these later.

7. To get your Ad Account ID, go to [Ads Manager](https://www.facebook.com/ads/manager) and it will be shown in the top right dropdown. Copy this numeric ID.

That covers the credentials needed! We will use these details later to generate an access token and make API calls.

Setting up the Python script

With the prerequisites installed and credentials obtained, we can now set up a Python script to extract the data.

Let’s start by importing the libraries we’ll need:

“`python
from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adsinsights import AdsInsights
import pandas as pd
“`

This imports the Facebook Ads API client along with AdAccount and AdsInsights classes we’ll use to make requests. We also import pandas to handle data transformations.

Next, we’ll initialize the API client with our credentials:

“`python
access_token = ‘

FacebookAdsApi.init(
app_id=’‘,
app_secret=’‘,
access_token=access_token
)
“`

Make sure to replace ``, `` and `` with the actual values we obtained earlier.

There are a couple ways to get the access token:

– Use the Graph API Explorer to generate a short-lived token
– Implement an OAuth login flow in your script to acquire a long-lived token

See [Facebook’s docs](https://developers.facebook.com/docs/facebook-login/access-tokens) for more details on access tokens.

Now the API client is initialized! Next we’ll write functions to make API calls.

Making API calls

We can use the Facebook Ads API endpoints to extract data for our ad accounts, ad sets, campaigns, ads and more. Let’s write Python functions to return this data.

First, a function to get a list of all ad accounts we have access to:

“`python
def get_ad_accounts():

accounts = AdAccount.get_by_ids(params={‘limit’:100})

return accounts
“`

This will return a list of AdAccount objects containing metadata like the account name, ID, spend etc.

To get insights for a specific ad account, we can use:

“`python
def get_insights(ad_account_id):

insights = AdsInsights(parent_id=ad_account_id)
insights.params[‘level’] = ‘ad’
insights = insights.get(
fields=[
‘campaign_name’,
‘adset_name’,
‘ad_name’,
‘impressions’,
‘clicks’,
‘spend’,
‘conversions’
],
params={‘limit’:100}
)

return insights
“`

This makes a call to get the latest insights for ads in that account, returning stats like impressions, clicks, spend etc.

We can pass different parent IDs and fields to get insights for ad sets, campaigns etc. And modify the `params` to do pagination, date filtering etc.

The [Facebook docs](https://developers.facebook.com/docs/marketing-api/reference/) provide details on all available endpoints and parameters.

Extracting data into Pandas

Now that we can make API calls, let’s extract the returned data into a Pandas dataframe for analysis.

We’ll start by getting a list of all ad accounts:

“`python
accounts = get_ad_accounts()
“`

Then extract insights for each account into its own dataframe:

“`python
dfs = [] # list to hold dataframes

for account in accounts:

insights = get_insights(account[‘account_id’])

df = pd.DataFrame(insights)

dfs.append(df)
“`

This loops through all ad accounts, gets insights for each, extracts into a dataframe and collects them in a list.

Finally, concatenate all dataframes into one:

“`python
data = pd.concat(dfs, ignore_index=True)
“`

Now `data` contains the combined insights across all accounts, ready for analysis!

Some key tasks you can do now:

– Filter, slice and dice data however needed
– Calculate additional metrics like ROAS, CPC etc.
– Summarize, plot and visualize data
– Export final output to CSV, Excel etc.

Let’s look at some examples!

Analyzing and visualizing data

With Pandas and Matplotlib, we can easily analyze and visualize the extracted data.

To group by campaign and get sum totals:

“`python
by_campaign = data.groupby(‘campaign_name’)[
‘impressions’, ‘clicks’, ‘spend’
].sum().reset_index()
“`

Calculate cost per click (CPC):

“`python
data[‘cpc’] = data[‘spend’] / data[‘clicks’]
“`

Plot ad CTR over time:

“`python
data.plot(
x=’date_start’,
y=’ctr’,
kind=’line’,
title=’CTR over Time’
)
“`

Filter to LGBTQ interest category and plot conversion rate:

“`python
lgbtq = data[data[‘interest_categories’] == ‘LGBTQ’]

lgbtq.plot(
x=’date_start’,
y=’conversion_rate’,
kind=’bar’
)
“`

These are just a few examples – the possibilities are endless! Pandas, Matplotlib and Python provide powerful tools to manipulate the data however you need.

Outputting data

Once pulled into Python, the data can be exported to share across your organization or integrate into other systems.

To export final output to a CSV:

“`python
data.to_csv(‘facebook_ads_data.csv’, index=False)
“`

This will save the dataframe to a CSV file, ready for opening in Excel.

You can also directly output to an Excel XLSX file using `pandas.ExcelWriter`.

For automated recurring reports, you may want to email the CSV output or upload to cloud storage like Amazon S3.

This covers the basics of exporting the extracted data. The key is getting it into a reusable format that can drive further analysis and optimization!

Conclusion

Extracting and analyzing Facebook ads data is crucial for optimizing your ad spend and impact. By leveraging Python and the Marketing API, you can efficiently pull any data you need on your campaigns. pandas enables powerful analysis and visualization capabilities to gain actionable insights.

The steps covered in this guide provide a framework to start extracting your Facebook ads data using Python:

– Install prerequisites like Python, Facebook SDK
– Obtain API credentials for your app
– Make API calls to extract insights data
– Load into pandas dataframes for transformation
– Analyze, visualize and export data as needed

Automating these data pulls with Python also makes the process quick, repeatable and scalable.

While this covers the basics, there are many ways to extend the code:

– Implement OAuth login flow for long-lived access token
– Schedule recurring scripts to refresh data
– Store data in databases like MySQL, BigQuery etc.
– Build interactive dashboards and apps on top of the data
– Integrate extracted data into business intelligence tools like Tableau

Optimizing Facebook ad performance takes experimentation and adaptation based on data. This guide provides the framework to efficiently access the data you need using Python. From there, the possibilities for custom analysis and optimization are endless!