• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3#
4# Copyright 2014 Google Inc. All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18"""Reference command-line example for Google Analytics Management API v3.
19
20This application demonstrates how to use the python client library to access
21all the pieces of data returned by the Google Analytics Management API v3.
22
23The application manages autorization by saving an OAuth2.0 token in a local
24file and reusing the token for subsequent requests. It then traverses the
25Google Analytics Management hiearchy. It first retrieves and prints all the
26authorized user's accounts, next it prints all the web properties for the
27first account, then all the profiles for the first web property and finally
28all the goals for the first profile. The sample then prints all the
29user's advanced segments.
30
31
32Before You Begin:
33
34Update the client_secrets.json file
35
36  You must update the clients_secrets.json file with a client id, client
37  secret, and the redirect uri. You get these values by creating a new project
38  in the Google APIs console and registering for OAuth2.0 for installed
39  applications: https://code.google.com/apis/console
40
41  Learn more about registering your analytics application here:
42  https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization
43
44Sample Usage:
45
46  $ python management_v3_reference.py
47
48Also you can also get help on all the command-line flags the program
49understands by running:
50
51  $ python management_v3_reference.py --help
52"""
53from __future__ import print_function
54
55__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
56
57import argparse
58import sys
59
60from googleapiclient.errors import HttpError
61from googleapiclient import sample_tools
62from oauth2client.client import AccessTokenRefreshError
63
64
65def main(argv):
66  # Authenticate and construct service.
67  service, flags = sample_tools.init(
68      argv, 'analytics', 'v3', __doc__, __file__,
69      scope='https://www.googleapis.com/auth/analytics.readonly')
70
71  # Traverse the Management hiearchy and print results or handle errors.
72  try:
73    traverse_hiearchy(service)
74
75  except TypeError as error:
76    # Handle errors in constructing a query.
77    print(('There was an error in constructing your query : %s' % error))
78
79  except HttpError as error:
80    # Handle API errors.
81    print(('Arg, there was an API error : %s : %s' %
82           (error.resp.status, error._get_reason())))
83
84  except AccessTokenRefreshError:
85    print ('The credentials have been revoked or expired, please re-run'
86           'the application to re-authorize')
87
88
89def traverse_hiearchy(service):
90  """Traverses the management API hiearchy and prints results.
91
92  This retrieves and prints the authorized user's accounts. It then
93  retrieves and prints all the web properties for the first account,
94  retrieves and prints all the profiles for the first web property,
95  and retrieves and prints all the goals for the first profile.
96
97  Args:
98    service: The service object built by the Google API Python client library.
99
100  Raises:
101    HttpError: If an error occured when accessing the API.
102    AccessTokenRefreshError: If the current token was invalid.
103  """
104
105  accounts = service.management().accounts().list().execute()
106  print_accounts(accounts)
107
108  if accounts.get('items'):
109    firstAccountId = accounts.get('items')[0].get('id')
110    webproperties = service.management().webproperties().list(
111        accountId=firstAccountId).execute()
112
113    print_webproperties(webproperties)
114
115    if webproperties.get('items'):
116      firstWebpropertyId = webproperties.get('items')[0].get('id')
117      profiles = service.management().profiles().list(
118          accountId=firstAccountId,
119          webPropertyId=firstWebpropertyId).execute()
120
121      print_profiles(profiles)
122
123      if profiles.get('items'):
124        firstProfileId = profiles.get('items')[0].get('id')
125        goals = service.management().goals().list(
126            accountId=firstAccountId,
127            webPropertyId=firstWebpropertyId,
128            profileId=firstProfileId).execute()
129
130        print_goals(goals)
131
132  print_segments(service.management().segments().list().execute())
133
134
135def print_accounts(accounts_response):
136  """Prints all the account info in the Accounts Collection.
137
138  Args:
139    accounts_response: The response object returned from querying the Accounts
140        collection.
141  """
142
143  print('------ Account Collection -------')
144  print_pagination_info(accounts_response)
145  print()
146
147  for account in accounts_response.get('items', []):
148    print('Account ID      = %s' % account.get('id'))
149    print('Kind            = %s' % account.get('kind'))
150    print('Self Link       = %s' % account.get('selfLink'))
151    print('Account Name    = %s' % account.get('name'))
152    print('Created         = %s' % account.get('created'))
153    print('Updated         = %s' % account.get('updated'))
154
155    child_link = account.get('childLink')
156    print('Child link href = %s' % child_link.get('href'))
157    print('Child link type = %s' % child_link.get('type'))
158    print()
159
160  if not accounts_response.get('items'):
161    print('No accounts found.\n')
162
163
164def print_webproperties(webproperties_response):
165  """Prints all the web property info in the WebProperties collection.
166
167  Args:
168    webproperties_response: The response object returned from querying the
169        Webproperties collection.
170  """
171
172  print('------ Web Properties Collection -------')
173  print_pagination_info(webproperties_response)
174  print()
175
176  for webproperty in webproperties_response.get('items', []):
177    print('Kind               = %s' % webproperty.get('kind'))
178    print('Account ID         = %s' % webproperty.get('accountId'))
179    print('Web Property ID    = %s' % webproperty.get('id'))
180    print(('Internal Web Property ID = %s' %
181           webproperty.get('internalWebPropertyId')))
182
183    print('Website URL        = %s' % webproperty.get('websiteUrl'))
184    print('Created            = %s' % webproperty.get('created'))
185    print('Updated            = %s' % webproperty.get('updated'))
186
187    print('Self Link          = %s' % webproperty.get('selfLink'))
188    parent_link = webproperty.get('parentLink')
189    print('Parent link href   = %s' % parent_link.get('href'))
190    print('Parent link type   = %s' % parent_link.get('type'))
191    child_link = webproperty.get('childLink')
192    print('Child link href    = %s' % child_link.get('href'))
193    print('Child link type    = %s' % child_link.get('type'))
194    print()
195
196  if not webproperties_response.get('items'):
197    print('No webproperties found.\n')
198
199
200def print_profiles(profiles_response):
201  """Prints all the profile info in the Profiles Collection.
202
203  Args:
204    profiles_response: The response object returned from querying the
205        Profiles collection.
206  """
207
208  print('------ Profiles Collection -------')
209  print_pagination_info(profiles_response)
210  print()
211
212  for profile in profiles_response.get('items', []):
213    print('Kind                      = %s' % profile.get('kind'))
214    print('Account ID                = %s' % profile.get('accountId'))
215    print('Web Property ID           = %s' % profile.get('webPropertyId'))
216    print(('Internal Web Property ID = %s' %
217           profile.get('internalWebPropertyId')))
218    print('Profile ID                = %s' % profile.get('id'))
219    print('Profile Name              = %s' % profile.get('name'))
220
221    print('Currency         = %s' % profile.get('currency'))
222    print('Timezone         = %s' % profile.get('timezone'))
223    print('Default Page     = %s' % profile.get('defaultPage'))
224
225    print(('Exclude Query Parameters        = %s' %
226           profile.get('excludeQueryParameters')))
227    print(('Site Search Category Parameters = %s' %
228           profile.get('siteSearchCategoryParameters')))
229    print(('Site Search Query Parameters    = %s' %
230           profile.get('siteSearchQueryParameters')))
231
232    print('Created          = %s' % profile.get('created'))
233    print('Updated          = %s' % profile.get('updated'))
234
235    print('Self Link        = %s' % profile.get('selfLink'))
236    parent_link = profile.get('parentLink')
237    print('Parent link href = %s' % parent_link.get('href'))
238    print('Parent link type = %s' % parent_link.get('type'))
239    child_link = profile.get('childLink')
240    print('Child link href  = %s' % child_link.get('href'))
241    print('Child link type  = %s' % child_link.get('type'))
242    print()
243
244  if not profiles_response.get('items'):
245    print('No profiles found.\n')
246
247
248def print_goals(goals_response):
249  """Prints all the goal info in the Goals collection.
250
251  Args:
252    goals_response: The response object returned from querying the Goals
253        collection
254  """
255
256  print('------ Goals Collection -------')
257  print_pagination_info(goals_response)
258  print()
259
260  for goal in goals_response.get('items', []):
261    print('Goal ID     = %s' % goal.get('id'))
262    print('Kind        = %s' % goal.get('kind'))
263    print('Self Link        = %s' % goal.get('selfLink'))
264
265    print('Account ID               = %s' % goal.get('accountId'))
266    print('Web Property ID          = %s' % goal.get('webPropertyId'))
267    print(('Internal Web Property ID = %s' %
268           goal.get('internalWebPropertyId')))
269    print('Profile ID               = %s' % goal.get('profileId'))
270
271    print('Goal Name   = %s' % goal.get('name'))
272    print('Goal Value  = %s' % goal.get('value'))
273    print('Goal Active = %s' % goal.get('active'))
274    print('Goal Type   = %s' % goal.get('type'))
275
276    print('Created     = %s' % goal.get('created'))
277    print('Updated     = %s' % goal.get('updated'))
278
279    parent_link = goal.get('parentLink')
280    print('Parent link href = %s' % parent_link.get('href'))
281    print('Parent link type = %s' % parent_link.get('type'))
282
283    # Print the goal details depending on the type of goal.
284    if goal.get('urlDestinationDetails'):
285      print_url_destination_goal_details(
286          goal.get('urlDestinationDetails'))
287
288    elif goal.get('visitTimeOnSiteDetails'):
289      print_visit_time_on_site_goal_details(
290          goal.get('visitTimeOnSiteDetails'))
291
292    elif goal.get('visitNumPagesDetails'):
293      print_visit_num_pages_goal_details(
294          goal.get('visitNumPagesDetails'))
295
296    elif goal.get('eventDetails'):
297      print_event_goal_details(goal.get('eventDetails'))
298
299    print()
300
301  if not goals_response.get('items'):
302    print('No goals found.\n')
303
304
305def print_url_destination_goal_details(goal_details):
306  """Prints all the URL Destination goal type info.
307
308  Args:
309    goal_details: The details portion of the goal response.
310  """
311
312  print('------ Url Destination Goal -------')
313  print('Goal URL            = %s' % goal_details.get('url'))
314  print('Case Sensitive      = %s' % goal_details.get('caseSensitive'))
315  print('Match Type          = %s' % goal_details.get('matchType'))
316  print('First Step Required = %s' % goal_details.get('firstStepRequired'))
317
318  print('------ Url Destination Goal Steps -------')
319  for goal_step in goal_details.get('steps', []):
320    print('Step Number  = %s' % goal_step.get('number'))
321    print('Step Name    = %s' % goal_step.get('name'))
322    print('Step URL     = %s' % goal_step.get('url'))
323
324  if not goal_details.get('steps'):
325    print('No Steps Configured')
326
327
328def print_visit_time_on_site_goal_details(goal_details):
329  """Prints all the Visit Time On Site goal type info.
330
331  Args:
332    goal_details: The details portion of the goal response.
333  """
334
335  print('------ Visit Time On Site Goal -------')
336  print('Comparison Type  = %s' % goal_details.get('comparisonType'))
337  print('comparison Value = %s' % goal_details.get('comparisonValue'))
338
339
340def print_visit_num_pages_goal_details(goal_details):
341  """Prints all the Visit Num Pages goal type info.
342
343  Args:
344    goal_details: The details portion of the goal response.
345  """
346
347  print('------ Visit Num Pages Goal -------')
348  print('Comparison Type  = %s' % goal_details.get('comparisonType'))
349  print('comparison Value = %s' % goal_details.get('comparisonValue'))
350
351
352def print_event_goal_details(goal_details):
353  """Prints all the Event goal type info.
354
355  Args:
356    goal_details: The details portion of the goal response.
357  """
358
359  print('------ Event Goal -------')
360  print('Use Event Value  = %s' % goal_details.get('useEventValue'))
361
362  for event_condition in goal_details.get('eventConditions', []):
363    event_type = event_condition.get('type')
364    print('Type             = %s' % event_type)
365
366    if event_type in ('CATEGORY', 'ACTION', 'LABEL'):
367      print('Match Type       = %s' % event_condition.get('matchType'))
368      print('Expression       = %s' % event_condition.get('expression'))
369    else:  # VALUE type.
370      print('Comparison Type  = %s' % event_condition.get('comparisonType'))
371      print('Comparison Value = %s' % event_condition.get('comparisonValue'))
372
373
374def print_segments(segments_response):
375  """Prints all the segment info in the Segments collection.
376
377  Args:
378    segments_response: The response object returned from querying the
379        Segments collection.
380  """
381
382  print('------ Segments Collection -------')
383  print_pagination_info(segments_response)
384  print()
385
386  for segment in segments_response.get('items', []):
387    print('Segment ID = %s' % segment.get('id'))
388    print('Kind       = %s' % segment.get('kind'))
389    print('Self Link  = %s' % segment.get('selfLink'))
390    print('Name       = %s' % segment.get('name'))
391    print('Definition = %s' % segment.get('definition'))
392    print('Created    = %s' % segment.get('created'))
393    print('Updated    = %s' % segment.get('updated'))
394    print()
395
396
397def print_pagination_info(management_response):
398  """Prints common pagination details.
399
400  Args:
401    management_response: The common reponse object for each collection in the
402        Management API.
403  """
404
405  print('Items per page = %s' % management_response.get('itemsPerPage'))
406  print('Total Results  = %s' % management_response.get('totalResults'))
407  print('Start Index    = %s' % management_response.get('startIndex'))
408
409  # These only have values if other result pages exist.
410  if management_response.get('previousLink'):
411    print('Previous Link  = %s' % management_response.get('previousLink'))
412  if management_response.get('nextLink'):
413    print('Next Link      = %s' % management_response.get('nextLink'))
414
415
416if __name__ == '__main__':
417  main(sys.argv)
418
419