Search code examples
facebookfacebook-graph-apifacebook-marketing-api

How to list custom audiences via Facebook API?


I can create audiences using the Facebook graph API, but is there a way to list audiences without knowing their ids?

import json, requests
response = requests.get(
    f"https://graph.facebook.com/v9.0/search?access_token={FB_TOKEN}",  #&fields={fields}",
    params=f"ad_account_id={AD_ACCOUNT_ID}",
    timeout=30
)
print(response.text)
print(json.dumps(response.json(), indent=4, sort_keys=False))

Only gets me this:

<Response [400]>
{
    "error": {
        "message": "(#27) This method is only available to Workplace apps.",
        "type": "OAuthException",
        "code": 27,
        "fbtrace_id": "xxx"
    }
}

Solution

  • Thanks to misorude's comment, this is the answer:

    import json, requests
    
    
    fields = "id,name,description"
    
    response = requests.get(
        f"https://graph.facebook.com/v9.0/{AD_ACCOUNT_ID}/customaudiences?access_token={FB_TOKEN}&fields={fields}",
        timeout=30
    )
    
    print(json.dumps(response.json(), indent=4, sort_keys=False))
    

    I also had to use f"https://graph.facebook.com/v9.0/me/adaccounts?access_token={FB_TOKEN}&fields={fields}", to get an AD_ACCOUNT_ID from the token to see that it should start with "act_" to avoid this error message:

    <Response [400]>
    {
        "error": {
            "message": "Unsupported get request. Object with ID 'xxx' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",
            "type": "GraphMethodException",
            "code": 100,
            "error_subcode": 33,
            "fbtrace_id": "xxx"
        }
    }