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 Core Reporting API v3. 19 20 This application demonstrates how to use the python client library to access 21 all the pieces of data returned by the Google Analytics Core Reporting API v3. 22 23 The application manages autorization by saving an OAuth2.0 token in a local 24 file and reusing the token for subsequent requests. 25 26 Before You Begin: 27 28 Update the client_secrets.json file 29 30 You must update the clients_secrets.json file with a client id, client 31 secret, and the redirect uri. You get these values by creating a new project 32 in the Google APIs console and registering for OAuth2.0 for installed 33 applications: https://code.google.com/apis/console 34 35 Learn more about registering your analytics application here: 36 http://developers.google.com/analytics/devguides/reporting/core/v3/gdataAuthorization 37 38 Supply your TABLE_ID 39 40 You will also need to identify from which profile to access data by 41 specifying the TABLE_ID constant below. This value is of the form: ga:xxxx 42 where xxxx is the profile ID. You can get the profile ID by either querying 43 the Management API or by looking it up in the account settings of the 44 Google Anlaytics web interface. 45 46 Sample Usage: 47 48 $ python core_reporting_v3_reference.py ga:xxxx 49 50 Where the table ID is used to identify from which Google Anlaytics profile 51 to retrieve data. This ID is in the format ga:xxxx where xxxx is the 52 profile ID. 53 54 Also you can also get help on all the command-line flags the program 55 understands by running: 56 57 $ python core_reporting_v3_reference.py --help 58 """ 59 from __future__ import print_function 60 61 __author__ = 'api.nickm (at] gmail.com (Nick Mihailovski)' 62 63 import argparse 64 import sys 65 66 from googleapiclient.errors import HttpError 67 from googleapiclient import sample_tools 68 from oauth2client.client import AccessTokenRefreshError 69 70 # Declare command-line flags. 71 argparser = argparse.ArgumentParser(add_help=False) 72 argparser.add_argument('table_id', type=str, 73 help=('The table ID of the profile you wish to access. ' 74 'Format is ga:xxx where xxx is your profile ID.')) 75 76 77 def main(argv): 78 # Authenticate and construct service. 79 service, flags = sample_tools.init( 80 argv, 'analytics', 'v3', __doc__, __file__, parents=[argparser], 81 scope='https://www.googleapis.com/auth/analytics.readonly') 82 83 # Try to make a request to the API. Print the results or handle errors. 84 try: 85 results = get_api_query(service, flags.table_id).execute() 86 print_results(results) 87 88 except TypeError as error: 89 # Handle errors in constructing a query. 90 print(('There was an error in constructing your query : %s' % error)) 91 92 except HttpError as error: 93 # Handle API errors. 94 print(('Arg, there was an API error : %s : %s' % 95 (error.resp.status, error._get_reason()))) 96 97 except AccessTokenRefreshError: 98 # Handle Auth errors. 99 print ('The credentials have been revoked or expired, please re-run ' 100 'the application to re-authorize') 101 102 103 def get_api_query(service, table_id): 104 """Returns a query object to retrieve data from the Core Reporting API. 105 106 Args: 107 service: The service object built by the Google API Python client library. 108 table_id: str The table ID form which to retrieve data. 109 """ 110 111 return service.data().ga().get( 112 ids=table_id, 113 start_date='2012-01-01', 114 end_date='2012-01-15', 115 metrics='ga:visits', 116 dimensions='ga:source,ga:keyword', 117 sort='-ga:visits', 118 filters='ga:medium==organic', 119 start_index='1', 120 max_results='25') 121 122 123 def print_results(results): 124 """Prints all the results in the Core Reporting API Response. 125 126 Args: 127 results: The response returned from the Core Reporting API. 128 """ 129 130 print_report_info(results) 131 print_pagination_info(results) 132 print_profile_info(results) 133 print_query(results) 134 print_column_headers(results) 135 print_totals_for_all_results(results) 136 print_rows(results) 137 138 139 def print_report_info(results): 140 """Prints general information about this report. 141 142 Args: 143 results: The response returned from the Core Reporting API. 144 """ 145 146 print('Report Infos:') 147 print('Contains Sampled Data = %s' % results.get('containsSampledData')) 148 print('Kind = %s' % results.get('kind')) 149 print('ID = %s' % results.get('id')) 150 print('Self Link = %s' % results.get('selfLink')) 151 print() 152 153 154 def print_pagination_info(results): 155 """Prints common pagination details. 156 157 Args: 158 results: The response returned from the Core Reporting API. 159 """ 160 161 print('Pagination Infos:') 162 print('Items per page = %s' % results.get('itemsPerPage')) 163 print('Total Results = %s' % results.get('totalResults')) 164 165 # These only have values if other result pages exist. 166 if results.get('previousLink'): 167 print('Previous Link = %s' % results.get('previousLink')) 168 if results.get('nextLink'): 169 print('Next Link = %s' % results.get('nextLink')) 170 print() 171 172 173 def print_profile_info(results): 174 """Prints information about the profile. 175 176 Args: 177 results: The response returned from the Core Reporting API. 178 """ 179 180 print('Profile Infos:') 181 info = results.get('profileInfo') 182 print('Account Id = %s' % info.get('accountId')) 183 print('Web Property Id = %s' % info.get('webPropertyId')) 184 print('Profile Id = %s' % info.get('profileId')) 185 print('Table Id = %s' % info.get('tableId')) 186 print('Profile Name = %s' % info.get('profileName')) 187 print() 188 189 190 def print_query(results): 191 """The query returns the original report query as a dict. 192 193 Args: 194 results: The response returned from the Core Reporting API. 195 """ 196 197 print('Query Parameters:') 198 query = results.get('query') 199 for key, value in query.iteritems(): 200 print('%s = %s' % (key, value)) 201 print() 202 203 204 def print_column_headers(results): 205 """Prints the information for each column. 206 207 The main data from the API is returned as rows of data. The column 208 headers describe the names and types of each column in rows. 209 210 211 Args: 212 results: The response returned from the Core Reporting API. 213 """ 214 215 print('Column Headers:') 216 headers = results.get('columnHeaders') 217 for header in headers: 218 # Print Dimension or Metric name. 219 print('\t%s name: = %s' % (header.get('columnType').title(), 220 header.get('name'))) 221 print('\tColumn Type = %s' % header.get('columnType')) 222 print('\tData Type = %s' % header.get('dataType')) 223 print() 224 225 226 def print_totals_for_all_results(results): 227 """Prints the total metric value for all pages the query matched. 228 229 Args: 230 results: The response returned from the Core Reporting API. 231 """ 232 233 print('Total Metrics For All Results:') 234 print('This query returned %s rows.' % len(results.get('rows'))) 235 print(('But the query matched %s total results.' % 236 results.get('totalResults'))) 237 print('Here are the metric totals for the matched total results.') 238 totals = results.get('totalsForAllResults') 239 240 for metric_name, metric_total in totals.iteritems(): 241 print('Metric Name = %s' % metric_name) 242 print('Metric Total = %s' % metric_total) 243 print() 244 245 246 def print_rows(results): 247 """Prints all the rows of data returned by the API. 248 249 Args: 250 results: The response returned from the Core Reporting API. 251 """ 252 253 print('Rows:') 254 if results.get('rows', []): 255 for row in results.get('rows'): 256 print('\t'.join(row)) 257 else: 258 print('No Rows Found') 259 260 261 if __name__ == '__main__': 262 main(sys.argv) 263