appsecret_proof – Facebook API | Python

By | 25/03/2021

Implementing the appsecret_proof was proving a little tricky as while it was relatively straight forward to generate the appsecret_proof, using it in API calls… just wasn’t working. Here are the docs

When you’re using GraphAPI you add it as a parameter, without it you’d receive the following error when making na API call:

API calls from the server require an appsecret_proof

Here’s how to get it working in Python.

First you need to enable Require App Secret in your app by heading to settings -> advanced and toggling it to on.

In your python code you first need to generate the appsecret_proof token, this is a hash of your app secret and access token (you’ll need to put your own app id, app secret & access token in here 🙂 )

from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.business import Business
from facebook_business import session

fb_sess = session.FacebookSession(app_id=app_id, app_secret=app_secret, access_token=access_token)
appsecret_proof = fb_sess._gen_appsecret_proof()

Generate a session by passing your ap_id, app_secret and access_token into FacebookSession

Calling _gen_appsecret_proof() on your session generates the appsecret_proof

We can then initialise a Facebook API connection

FacebookAdsApi.init(access_token=access_token, api_version='v10.0')

Let’s create a Facebook Business object and get the owned ad accounts.

business = Business(business_manager_id)

Now let’s call the get_owned_ad_accounts method and get the names of the accounts.

adAccounts = business.get_owned_ad_accounts(fields=['name'])

Without the appsecret_proof you’ll get the following error:

Status: 400
    Response:
        {
            "error": {
            "message": "API calls from the server require an appsecret_proof             argument",
            "type": "GraphMethodException",
            "code": 100,
            "fbtrace_id": "AK7tEgqLZHuFCWeqY2uou1v"
            }
        }

To allow the API call you’ll need to pass in the appsecret_proof as a parameter as follows:

adAccounts = business.get_owned_ad_accounts(params={'appsecret_proof': appsecret_proof})

Ensure the key is ‘appsecret_proof’ as a string and the appsecret_proof is the variable generated previously.

To secure API calls it’s worth separating the code to generate the appsecret_proof from other code making the api calls, even holding all 4 App variables in separate secrets managers.