A Beginner's Guide to Facebook Marketing API with Python

·

5 min read

Facebook Marketing API allows developers and marketers to create and manage their Facebook ad campaigns more efficiently through a programmatic interface. This beginner's guide will introduce you to the basics of using the Facebook Marketing API with Python, covering essential topics such as authentication, working with accounts, retrieving campaign data, and fetching campaign insights. By the end of this guide, you should have a solid understanding of how to integrate the API into your marketing strategies and harness its full potential.

Requirements

  • facebook_business. This is the official Facebook Python SDK. See its GitHub page.

  • requests-oauthlib. Python OAuth library that we can use to authenticate to Facebook. For more info, see Requests-OAuthlib.

Before We Begin

To use Facebook API, we need to have App ID, App Secret and Access Token. The Access Token is something that you need to generate. But the App ID and App Secret are something you get from the Facebook app dashboard.

That means we need to create an app before we can start using the API. You can create an app from the Facebook developer website. Here is a short guide on how to create a new app.

How to create a Facebook App

Once you have created an application, you will have access to the App ID and the App Secret from the App Settings > Basic menu.

Where to get App ID and App Secret

Access Token

To get an access token, we can use the requests_oauthlib


from requests_oauthlib.compliance_fixes import facebook_compliance_fix

my_app_id = "<app id>"
my_app_secret = "<app secret>"

authorization_base_url = "https://www.facebook.com/v18.0/dialog/oauth"
token_url = "https://graph.facebook.com/v18.0/oauth/access_token" 
redirect_uri = "https://localhost/" 

facebook = OAuth2Session(
    my_app_id,
    redirect_uri=redirect_uri,
    scope="ads_management,ads_read"
)
facebook = facebook_compliance_fix(facebook)

# Print the authorization URL. Access the URL using your browser.
authorization_url, state = facebook.authorization_url(authorization_base_url)
print(f"Please go here and authorize: {authorization_url}")

# Wait for the user to input the redirect URL
redirect_response = input("Paste the full redirect URL here:")

# Get the token
token = facebook.fetch_token(token_url, client_secret=my_app_secret,
                              authorization_response=redirect_response)

When you run the code above in a terminal, it will print out an authorization_url. And wait for you to paste the redirect URL. You then need to use your browser to open the link. Facebook will ask for your consent, and if everything goes well, you will be redirected to a blank page. Don't be alarmed. All you need to do now is copy the whole URL from your browser location bar and paste it into the terminal that is waiting. Once you are done, we can finally get the access token.

The token variable will have something like:

{'access_token': '<access_token>',
 'token_type': 'bearer',
 'expires_in': 5132946,
 'expires_at': 1703429997.4087522}

Now that we have all the needed items, we can continue playing around with the API.

Authorization and Authentication

Before making any API calls, we need to invoke the FacebookAdsApi.init. This method sets up a default FacebooksAdsApi object to be used.

from facebook_business.api import FacebookAdsApi

my_app_id = "<app_id>"
my_app_secret = "<app_secret>"
my_access_token = "<app_token>"

FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)

Getting Accounts

The first API we will try is getting the account. The simplest way is to use the User class with the fbid="me" parameters.

from facebook_business.adobjects.user import User

me = User(fbid="me")
my_accounts = list(me.get_ad_accounts(
    fields=["account_id", "id", "name"])
)

The my_accounts will have something like the following.

[<AdAccount> {
     "account_id": "<account id>",
     "id": "act_<account id>",
     "name": "Account 1"
 },
 <AdAccount> {
     "account_id": "<account id>",
     "id": "act_<account id>",
     "name": "Account 2"
 }]

Great. We just made our first API call.

A brief note: Although the method above is functional, it has a minor issue. It retrieves all accounts linked to your Facebook account. If you possess a lot of accounts, managing them could become challenging.

The alternative to this approach is to use a Business account. On Facebook, you can create a Business and establish an app associated with that business. This method makes it easier to manage, even if you have a lot of ad accounts. You can do the following to obtain accounts associated with a specific business.

from facebook_business.adobjects.application import Application
from facebook_business.api import FacebookAdsApi

FacebookAdsApi.init(business_id, my_app_secret, my_access_token)

app = Application(fbid=business_id)
my_accounts = list(app.get_authorized_ad_accounts(
    fields=["id", "account_id", "name"])
)

Getting Campaigns

Now that you get the account list. How do we get campaigns for all those accounts? Use the AdAccount class and invoke the get_campaigns method.

from facebook_business.adobjects.adaccount import AdAccount

campaign_list = []
for account in my_accounts:
    my_account = AdAccount(account["id"])
    campaigns = my_account.get_campaigns(
        fields=["id", "account_id", "name"]
    )
    campaign_list.extend(campaigns)

The campaign_list will look something like:

[<Campaign> {
    "account_id": "<account_id>",
    "id": "<campaign_id>",
    "name": "<campaign_name>"
}, ...]

Getting Campaigns Insight

To get campaign insight, we can run get_insights with the level set to the campaign. This will get the campaign cost in bulk. The alternative is to get the campaign list for the account, loop through each campaign, and fetch the insight data. This will deplete your API rate limit. But of course, we must be aware of the amount of data. We will be using yesterday as the date_preset in the example below, so this might not be a problem. But if the data gets big and causes time out, you need to switch to the async version (the SDK provides this but requires a bit more handling).

from facebook_business.adobjects.adaccount import AdAccount

insight_list = []
for account in my_accounts:
    my_account = AdAccount(account["id"])
    insight = my_account.get_insights(
        fields=["account_id", "account_name", 
                "campaign_id", "campaign_name",
                "date_start", "date_stop", "spend"],
        params={"date_preset":"yesterday ",   
                "level":"campaign"})
    insight_list.extend(insight)

For the above example, I only get the spend data. There are other data you can get, like impression, cpc, cpm, etc.

When we run the code above, the insight_list will look something like the following.

[[<AdsInsights> {
     "account_id": "<account id>",
     "account_name": "<account name>",
     "campaign_id": "<campaign id>",
     "campaign_name": "<campaign name>",
     "date_start": "<yesterday date>",
     "date_stop": "<today date>",
     "spend": "<the cost>"
 }, ...]

Summary

The Facebook Marketing API offers a powerful and efficient way to manage your ad campaigns programmatically. By using Python and the official SDK, you can easily authenticate, retrieve accounts, fetch campaign data, and gain insights into your campaign costs. With this foundational knowledge, you can now start integrating the API into your marketing strategies and harness its full potential to optimize your advertising efforts on Facebook.