OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/python |
| 2 # -*- coding: utf-8 -*- |
| 3 # |
| 4 # Copyright 2012 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://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html |
| 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 |
| 49 |
| 50 Also you can also get help on all the command-line flags the program |
| 51 understands by running: |
| 52 |
| 53 $ python core_reporting_v3_reference.py --help |
| 54 """ |
| 55 |
| 56 __author__ = 'api.nickm@gmail.com (Nick Mihailovski)' |
| 57 |
| 58 import sys |
| 59 import sample_utils |
| 60 |
| 61 from apiclient.errors import HttpError |
| 62 from oauth2client.client import AccessTokenRefreshError |
| 63 |
| 64 |
| 65 # The table ID is used to identify from which Google Anlaytics profile |
| 66 # to retrieve data. This ID is in the format ga:xxxx where xxxx is the |
| 67 # profile ID. |
| 68 TABLE_ID = 'INSERT_YOUR_TABLE_ID_HERE' |
| 69 |
| 70 |
| 71 def main(argv): |
| 72 sample_utils.process_flags(argv) |
| 73 |
| 74 # Authenticate and construct service. |
| 75 service = sample_utils.initialize_service() |
| 76 |
| 77 # Try to make a request to the API. Print the results or handle errors. |
| 78 try: |
| 79 results = get_api_query(service).execute() |
| 80 print_results(results) |
| 81 |
| 82 except TypeError, error: |
| 83 # Handle errors in constructing a query. |
| 84 print ('There was an error in constructing your query : %s' % error) |
| 85 |
| 86 except HttpError, error: |
| 87 # Handle API errors. |
| 88 print ('Arg, there was an API error : %s : %s' % |
| 89 (error.resp.status, error._get_reason())) |
| 90 |
| 91 except AccessTokenRefreshError: |
| 92 # Handle Auth errors. |
| 93 print ('The credentials have been revoked or expired, please re-run ' |
| 94 'the application to re-authorize') |
| 95 |
| 96 |
| 97 def get_api_query(service): |
| 98 """Returns a query object to retrieve data from the Core Reporting API. |
| 99 |
| 100 Args: |
| 101 service: The service object built by the Google API Python client library. |
| 102 """ |
| 103 |
| 104 return service.data().ga().get( |
| 105 ids=TABLE_ID, |
| 106 start_date='2012-01-01', |
| 107 end_date='2012-01-15', |
| 108 metrics='ga:visits', |
| 109 dimensions='ga:source,ga:keyword', |
| 110 sort='-ga:visits', |
| 111 filters='ga:medium==organic', |
| 112 start_index='1', |
| 113 max_results='25') |
| 114 |
| 115 |
| 116 def print_results(results): |
| 117 """Prints all the results in the Core Reporting API Response. |
| 118 |
| 119 Args: |
| 120 results: The response returned from the Core Reporting API. |
| 121 """ |
| 122 |
| 123 print_report_info(results) |
| 124 print_pagination_info(results) |
| 125 print_profile_info(results) |
| 126 print_query(results) |
| 127 print_column_headers(results) |
| 128 print_totals_for_all_results(results) |
| 129 print_rows(results) |
| 130 |
| 131 |
| 132 def print_report_info(results): |
| 133 """Prints general information about this report. |
| 134 |
| 135 Args: |
| 136 results: The response returned from the Core Reporting API. |
| 137 """ |
| 138 |
| 139 print 'Report Infos:' |
| 140 print 'Contains Sampled Data = %s' % results.get('containsSampledData') |
| 141 print 'Kind = %s' % results.get('kind') |
| 142 print 'ID = %s' % results.get('id') |
| 143 print 'Self Link = %s' % results.get('selfLink') |
| 144 print |
| 145 |
| 146 |
| 147 def print_pagination_info(results): |
| 148 """Prints common pagination details. |
| 149 |
| 150 Args: |
| 151 results: The response returned from the Core Reporting API. |
| 152 """ |
| 153 |
| 154 print 'Pagination Infos:' |
| 155 print 'Items per page = %s' % results.get('itemsPerPage') |
| 156 print 'Total Results = %s' % results.get('totalResults') |
| 157 |
| 158 # These only have values if other result pages exist. |
| 159 if results.get('previousLink'): |
| 160 print 'Previous Link = %s' % results.get('previousLink') |
| 161 if results.get('nextLink'): |
| 162 print 'Next Link = %s' % results.get('nextLink') |
| 163 print |
| 164 |
| 165 |
| 166 def print_profile_info(results): |
| 167 """Prints information about the profile. |
| 168 |
| 169 Args: |
| 170 results: The response returned from the Core Reporting API. |
| 171 """ |
| 172 |
| 173 print 'Profile Infos:' |
| 174 info = results.get('profileInfo') |
| 175 print 'Account Id = %s' % info.get('accountId') |
| 176 print 'Web Property Id = %s' % info.get('webPropertyId') |
| 177 print 'Profile Id = %s' % info.get('profileId') |
| 178 print 'Table Id = %s' % info.get('tableId') |
| 179 print 'Profile Name = %s' % info.get('profileName') |
| 180 print |
| 181 |
| 182 |
| 183 def print_query(results): |
| 184 """The query returns the original report query as a dict. |
| 185 |
| 186 Args: |
| 187 results: The response returned from the Core Reporting API. |
| 188 """ |
| 189 |
| 190 print 'Query Parameters:' |
| 191 query = results.get('query') |
| 192 for key, value in query.iteritems(): |
| 193 print '%s = %s' % (key, value) |
| 194 print |
| 195 |
| 196 |
| 197 def print_column_headers(results): |
| 198 """Prints the information for each column. |
| 199 |
| 200 The main data from the API is returned as rows of data. The column |
| 201 headers describe the names and types of each column in rows. |
| 202 |
| 203 |
| 204 Args: |
| 205 results: The response returned from the Core Reporting API. |
| 206 """ |
| 207 |
| 208 print 'Column Headers:' |
| 209 headers = results.get('columnHeaders') |
| 210 for header in headers: |
| 211 # Print Dimension or Metric name. |
| 212 print '\t%s name: = %s' % (header.get('columnType').title(), |
| 213 header.get('name')) |
| 214 print '\tColumn Type = %s' % header.get('columnType') |
| 215 print '\tData Type = %s' % header.get('dataType') |
| 216 print |
| 217 |
| 218 |
| 219 def print_totals_for_all_results(results): |
| 220 """Prints the total metric value for all pages the query matched. |
| 221 |
| 222 Args: |
| 223 results: The response returned from the Core Reporting API. |
| 224 """ |
| 225 |
| 226 print 'Total Metrics For All Results:' |
| 227 print 'This query returned %s rows.' % len(results.get('rows')) |
| 228 print ('But the query matched %s total results.' % |
| 229 results.get('totalResults')) |
| 230 print 'Here are the metric totals for the matched total results.' |
| 231 totals = results.get('totalsForAllResults') |
| 232 |
| 233 for metric_name, metric_total in totals.iteritems(): |
| 234 print 'Metric Name = %s' % metric_name |
| 235 print 'Metric Total = %s' % metric_total |
| 236 print |
| 237 |
| 238 |
| 239 def print_rows(results): |
| 240 """Prints all the rows of data returned by the API. |
| 241 |
| 242 Args: |
| 243 results: The response returned from the Core Reporting API. |
| 244 """ |
| 245 |
| 246 print 'Rows:' |
| 247 if results.get('rows', []): |
| 248 for row in results.get('rows'): |
| 249 print '\t'.join(row) |
| 250 else: |
| 251 print 'No Rows Found' |
| 252 |
| 253 |
| 254 if __name__ == '__main__': |
| 255 main(sys.argv) |
OLD | NEW |