Unable to connect via Python (twitter-ads)


#1

I have a very simple program that I am trying to get to work, when I execute I get an error 401 (UNAUTHORIZED ACCESS), the account I am trying to tie to is my account, so I have full access to it (my assumption). I have a feeling I am missing a step somewhere, just don’t know where.

What we are after is the ability to pull analytics from our various clients that we have access to.

from twitter_ads.client import Client
from twitter_ads.campaign import Campaign
from twitter_ads.enum import ENTITY_STATUS

CONSUMER_KEY = '****'
CONSUMER_SECRET = '****'
ACCESS_TOKEN = '****'
ACCESS_TOKEN_SECRET = '****'
ACCOUNT_ID = '****' # account ID pulled from ads.twitter.com/ads_manager

# initialize the client
client = Client(
    CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

# load the advertiser account instance
account = client.accounts(ACCOUNT_ID)

# iterate through campaigns
for campaign in account.campaigns():
    print(campaign.id)

#2

The UNAUTHORIZED ACCESS response usually indicate that one of the environment variables provided is incorrect or the credentials don’t have access to that Account.

Could you verify that each of the environment variables you’ve set up match those from your Ads API-enabled application?

If those are correct, it would be helpful to verify that the credentials can access the Ads API. Can you confirm that the following command shows they have access to an Ads account using Twurl

twurl -H "https://ads-api.twitter.com" "/5/accounts/"

or using the command line helper for Python:

~ ❯ twitter-ads
❯❯❯ CLIENT.accounts().count

If those succeed, please verify the access to the account using the authenticated-user-access endpoint?

twurl -H "https://ads-api.twitter.com" "/5/accounts/$ACCOUNT/authenticated_user_access"


#3

When I do:

twurl -H "https://ads-api.twitter.com" "/5/accounts/"

I get back a very large response.

When I do:

~ ❯ twitter-ads
❯❯❯ CLIENT.accounts().count

I get back 79

when I do:

twurl -H "https://ads-api.twitter.com" "/5/accounts/$ACCOUNT/authenticated_user_access"

changing out $ACCOUNT for the account I am trying to access, I get the following:

{“data”:{“user_id”:***,“permissions”:[“CAMPAIGN_ANALYST”]},“request”:{“params”:{“account_id”:"***"}}}

So it looks like everything works that you suggested.


#4

It looks like Twurl is using credentials to successfully connect to the $ACCOUNT and indicates that something is incorrect with the Python variables. Can you verify that the Python data matches the credentials that are returned for the (default) value returned from twurl accounts?


#5

You are correct, I was literally one letter off on the access token in the above code, all is working now, this can be closed, thank you!