Get Campaign data for Ad Accounts using the Facebook Marketing API

In the last post we extracted both the Owned & Client Ad Accounts under a BM, from the Ad Account layer we can hit a number of edges so to start with let’s extract the Campaign Data

We’ll eventually extract all this data via a graph query and you’ll see how easy it is to get nested data but for now we’ll carry in using the Python SDK. Here’s the link to the Facebook Developer Docs for Campaigns

So from the last post we had an allAdAccount list we built up using the code below… don’t forget to initialise a connection to the Facebook API before making any calls.

allAdAccounts = list()

fields = ['name', 'account_status']

business = Business(bm_id)

ownedAdAccounts = business.get_owned_ad_accounts(fields=fields, params=params)

[allAdAccounts.append({'id': adAcc['id'],
'name': adAcc['name'],
'account_status': adAcc['account_status']})
for adAcc in ownedAdAccounts
if adAcc['account_status'] == 1]

To get Campaign data we need to iterate through each AdAccount and hit the Campaign Edge, let’s create a list to hold the campaigns data and set the fields we need to extract.

# Create a list to hold all the campaign Data
campaignData = list()

# Set campaign Fields
fields = ['name', 'created_time', 'objective', 'status']

We can now loop through the allAdAccounts list and extract the campaign data for each:

for adAcc in allAdAccounts[:2]:
    acc_id = adAcc['id']
    campaigns = AdAccount(acc_id).get_campaigns(fields=fields)
    for campaign in campaigns:
        campaignData.append({'id': campaign['id'],
                             'name': campaign['name'],
                             'created_time': campaign['created_time'],
                             'objective': campaign['objective'],
                             'status': campaign['status']
                             })

We can tidy this up a little:

for adAcc in allAdAccounts:
    [campaignData.append({'account_id': campaign['account_id'],
                          'id': campaign['id'],
                          'name': campaign['name'],
                          'created_time': campaign['created_time'],
                          'objective': campaign['objective'],
                          'status': campaign['status']
                          })
     for campaign
     in AdAccount(adAcc['id']).get_campaigns(fields=fields)]

We now have a list of all campaigns for all the Ad Accounts under a Business Manager. You can see how with this iterative approach you can build up a relational dataset one layer at a time, or if you only need data for a specific AdAccount(s) you can create a list of the Ad Accounts you want to extract the Campaigns for and use that as the allAdAccounts list.

In the next post we’ll look at how to get AdSet data both from theAdAccount & Campaign Edges