There are multiple dimensions and metrics that I want to pull from Google Analytics via their API, and this requires dimension:metric(s) pairing. Naturally, I thought dictionary might be a good option for this. To minimize typing, and increase readability, this is what I tried.
dim_dict = {
0:'',
1:'ga:searchUsed',
2:'ga:searchKeyword',
3:'ga:pageTitle',
4:'ga:operatingSystem',
5:'ga:goalPreviousStep3'
}
metric_dict = {
1:'ga:sessions',
2:'ga:sessionDuration',
3:'bounceRate',
4:'pageviews',
5:'ga:searchSessions',
6:'ga:goalCompletionsAll'
}
dim_metric_dict = {
0:[1,2,3,4,5,6],
1:[1,2,3,4,5,6],
2:[1,2,3,4,5,6],
3:[1,2,3,4,5,6],
4:[1,2,3,4,5,6],
5:[6]
}
query_dict = {}
for dim_key in dim_dict.keys():
met = []
for metric_key in dim_metric_dict[dim_key]:
met.append(metric_dict[metric_key])
query_dict.update({dim_dict[dim_key]:met})
Then, I'm using the following code to make API requests:
def get_ga_kpi(start_date, end_date, dimensions='', sort='ga:pageviews'):
service = build('analytics', 'v3', http=http)
metrics = query_dict[dimensions]
if sort not in metrics:
sort = metrics[0]
data_query = service.data().ga().get(**{
'ids': 'ga:#######',
'metrics': '%s' % (','.join(metrics)),
'dimensions': '%s' % (dimensions),
'start_date':'%s' % (start_date),
'end_date':'%s' % (end_date),
'sort': '-%s' % (sort)
})
return feed['rows']
The code works as intended, but I'm wondering if there is a better way to approach this problem. Thanks for any input!