Adding Users with multiple keys to a Custom Audience using Python facebook marketing API

1.2k views Asked by At

I need to create a custom audience with multi keys of users such as:

+-----------+------+-----+----------------------+------------+
| EXTERN_ID |  FN  | LN  |        EMAIL         |   PHONE    |
+-----------+------+-----+----------------------+------------+
|     12345 | John | Doe | [email protected] | 1234567890 |
+-----------+------+-----+----------------------+------------+

I can create a custom audience with the below given code:

from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.customaudience import CustomAudience
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS TOKEN>'
app_secret = '<APP SECRET>'
app_id = '<APP ID>'
id = '<ACCNT_ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
]
params = {
  'name': 'TEST',
  'subtype': 'CUSTOM',
  'description': 'Internal Data',
  'customer_file_source': 'USER_PROVIDED_ONLY',
}
print(AdAccount(id).create_custom_audience(
  fields=fields,
  params=params,
))

But, how to add multi-key user values to the created audience? I'm pretty new to Python and Facebook SDK. Any help will be really appreciated.

1

There are 1 answers

0
Matteo On BEST ANSWER

You could add users to the just created Custom Audience creating a

// Define your schema
schema = [
            customaudience.CustomAudience.Schema.MultiKeySchema.extern_id,
            customaudience.CustomAudience.Schema.MultiKeySchema.fn,
            customaudience.CustomAudience.Schema.MultiKeySchema.ln,
            customaudience.CustomAudience.Schema.MultiKeySchema.email,
            customaudience.CustomAudience.Schema.MultiKeySchema.phone,
        ]

// create the payload
payload = customaudience.CustomAudience.format_params(
            schema,[
                    ["12345", "John", "Doe", "[email protected]","1234567890"],
                   ],
            is_raw=True,
        )

Then you can use the payload, as example:

AdAccount(id).get_api_assured().call(
            'POST',
            ('<custom-audience-id>', 'users'),
            params=payload,
        )

Further Reference:

https://developers.facebook.com/docs/marketing-api/reference/sdks/python/custom-audience/v8.0

https://github.com/facebook/facebook-python-business-sdk/blob/master/facebook_business/adobjects/helpers/customaudiencemixin.py

https://github.com/facebook/facebook-python-business-sdk/blob/e2f279a62b7e6c7fd30a080b4be8103c7303a715/facebook_business/test/docs.py