Getting started


#1

I have authenticated, twurl is setup, and the Get Started code from twitter-python-ads-sdk runs… so now what? How do I translate an API call like this

"GET https://ads-api.twitter.com/2/stats/accounts/18ce54d4x5t?entity=LINE_ITEM&entity_ids=8u94t&start_time=2017-05-19&end_time=2017-05-26&granularity=TOTAL&placement=ALL_ON_TWITTER&metric_groups=ENGAGEMENT"

into an actual python script?

Background info: I’m trying to retrieve engagement metrics (similar to the ones found by manually exporting the data in the Ads webpage). But crawling before walking, I just want to use some of the Ads API calls. The example analytics.py script in the SDK doesn’t make sense to me as I don’t see how it relates back to the GET/POST API requests.

Any help or sample code to get me started?


#2

Hi, @3M_Canada.

In terms of requesting stats using the GET stats/account/:account_id endpoint with Python, there are various ways to do this. As you mentioned, one way is using the Python SDK. For a Python example where it’s clear to see how the script relates to the API call, see below. (This uses requests and requests-oauthlib.)

>>> import requests
>>> from requests_oauthlib import OAuth1
>>> 
>>> CONSUMER_KEY = ""
>>> CONSUMER_SECRET = ""
>>> TOKEN = ""
>>> TOKEN_SECRET = ""
>>> 
>>> auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, TOKEN, TOKEN_SECRET)
>>> 
>>> url = "https://ads-api.twitter.com/2/stats/accounts/18ce54d4x5t"
>>>
>>> params = {"entity" : "LINE_ITEM", "entity_ids" : "8u94t",
...           "start_time" : "2017-05-19", "end_time" : "2017-05-26",
...           "granularity" : "TOTAL", "placement" : "ALL_ON_TWITTER",
...           "metric_groups" : "ENGAGEMENT"}
>>>
>>> r = requests.get(url, auth=auth, params=params)
>>> r.status_code
200
>>> r.json()
{  
  'data_type':'stats',
  'time_series_length':1,
  'request':{  
    'params':{  
      'start_time':'2017-05-19T07:00:00Z',
      'end_time':'2017-05-26T07:00:00Z',
      'segmentation_type':None,
      'platform':None,
      'entity_ids':[  
        '8u94t'
      ],
      'placement':'ALL_ON_TWITTER',
      'entity':'LINE_ITEM',
      'country':None,
      'metric_groups':[  
        'ENGAGEMENT'
      ],
      'granularity':'TOTAL'
    }
  },
  'data':[  
    {  
      'id_data':[  
        {  
          'metrics':{  
            'carousel_swipes':None,
            'follows':None,
            'qualified_impressions':None,
            'retweets':None,
            'replies':None,
            'impressions':[  
              1233
            ],
            'engagements':[  
              58
            ],
            'poll_card_vote':None,
            'url_clicks':None,
            'tweets_send':None,
            'likes':[  
              1
            ],
            'app_clicks':None,
            'card_engagements':None,
            'clicks':[  
              58
            ]
          },
          'segment':None
        }
      ],
      'id':'8u94t'
    }
  ]
}

Hope this helps!