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 """Simple intro to using the Google Analytics API v3. |
| 19 |
| 20 This application demonstrates how to use the python client library to access |
| 21 Google Analytics data. The sample traverses the Management API to obtain the |
| 22 authorized user's first profile ID. Then the sample uses this ID to |
| 23 contstruct a Core Reporting API query to return the top 25 organic search |
| 24 terms. |
| 25 |
| 26 Before you begin, you must sigup for a new project in the Google APIs console: |
| 27 https://code.google.com/apis/console |
| 28 |
| 29 Then register the project to use OAuth2.0 for installed applications. |
| 30 |
| 31 Finally you will need to add the client id, client secret, and redirect URL |
| 32 into the client_secrets.json file that is in the same directory as this sample. |
| 33 |
| 34 Sample Usage: |
| 35 |
| 36 $ python hello_analytics_api_v3.py |
| 37 |
| 38 Also you can also get help on all the command-line flags the program |
| 39 understands by running: |
| 40 |
| 41 $ python hello_analytics_api_v3.py --help |
| 42 """ |
| 43 |
| 44 __author__ = 'api.nickm@gmail.com (Nick Mihailovski)' |
| 45 |
| 46 import sys |
| 47 import sample_utils |
| 48 |
| 49 from apiclient.errors import HttpError |
| 50 from oauth2client.client import AccessTokenRefreshError |
| 51 |
| 52 |
| 53 def main(argv): |
| 54 sample_utils.process_flags(argv) |
| 55 |
| 56 # Authenticate and construct service. |
| 57 service = sample_utils.initialize_service() |
| 58 |
| 59 # Try to make a request to the API. Print the results or handle errors. |
| 60 try: |
| 61 first_profile_id = get_first_profile_id(service) |
| 62 if not first_profile_id: |
| 63 print 'Could not find a valid profile for this user.' |
| 64 else: |
| 65 results = get_top_keywords(service, first_profile_id) |
| 66 print_results(results) |
| 67 |
| 68 except TypeError, error: |
| 69 # Handle errors in constructing a query. |
| 70 print ('There was an error in constructing your query : %s' % error) |
| 71 |
| 72 except HttpError, error: |
| 73 # Handle API errors. |
| 74 print ('Arg, there was an API error : %s : %s' % |
| 75 (error.resp.status, error._get_reason())) |
| 76 |
| 77 except AccessTokenRefreshError: |
| 78 # Handle Auth errors. |
| 79 print ('The credentials have been revoked or expired, please re-run ' |
| 80 'the application to re-authorize') |
| 81 |
| 82 |
| 83 def get_first_profile_id(service): |
| 84 """Traverses Management API to return the first profile id. |
| 85 |
| 86 This first queries the Accounts collection to get the first account ID. |
| 87 This ID is used to query the Webproperties collection to retrieve the first |
| 88 webproperty ID. And both account and webproperty IDs are used to query the |
| 89 Profile collection to get the first profile id. |
| 90 |
| 91 Args: |
| 92 service: The service object built by the Google API Python client library. |
| 93 |
| 94 Returns: |
| 95 A string with the first profile ID. None if a user does not have any |
| 96 accounts, webproperties, or profiles. |
| 97 """ |
| 98 |
| 99 accounts = service.management().accounts().list().execute() |
| 100 |
| 101 if accounts.get('items'): |
| 102 firstAccountId = accounts.get('items')[0].get('id') |
| 103 webproperties = service.management().webproperties().list( |
| 104 accountId=firstAccountId).execute() |
| 105 |
| 106 if webproperties.get('items'): |
| 107 firstWebpropertyId = webproperties.get('items')[0].get('id') |
| 108 profiles = service.management().profiles().list( |
| 109 accountId=firstAccountId, |
| 110 webPropertyId=firstWebpropertyId).execute() |
| 111 |
| 112 if profiles.get('items'): |
| 113 return profiles.get('items')[0].get('id') |
| 114 |
| 115 return None |
| 116 |
| 117 |
| 118 def get_top_keywords(service, profile_id): |
| 119 """Executes and returns data from the Core Reporting API. |
| 120 |
| 121 This queries the API for the top 25 organic search terms by visits. |
| 122 |
| 123 Args: |
| 124 service: The service object built by the Google API Python client library. |
| 125 profile_id: String The profile ID from which to retrieve analytics data. |
| 126 |
| 127 Returns: |
| 128 The response returned from the Core Reporting API. |
| 129 """ |
| 130 |
| 131 return service.data().ga().get( |
| 132 ids='ga:' + profile_id, |
| 133 start_date='2012-01-01', |
| 134 end_date='2012-01-15', |
| 135 metrics='ga:visits', |
| 136 dimensions='ga:source,ga:keyword', |
| 137 sort='-ga:visits', |
| 138 filters='ga:medium==organic', |
| 139 start_index='1', |
| 140 max_results='25').execute() |
| 141 |
| 142 |
| 143 def print_results(results): |
| 144 """Prints out the results. |
| 145 |
| 146 This prints out the profile name, the column headers, and all the rows of |
| 147 data. |
| 148 |
| 149 Args: |
| 150 results: The response returned from the Core Reporting API. |
| 151 """ |
| 152 |
| 153 print |
| 154 print 'Profile Name: %s' % results.get('profileInfo').get('profileName') |
| 155 print |
| 156 |
| 157 # Print header. |
| 158 output = [] |
| 159 for header in results.get('columnHeaders'): |
| 160 output.append('%30s' % header.get('name')) |
| 161 print ''.join(output) |
| 162 |
| 163 # Print data table. |
| 164 if results.get('rows', []): |
| 165 for row in results.get('rows'): |
| 166 output = [] |
| 167 for cell in row: |
| 168 output.append('%30s' % cell) |
| 169 print ''.join(output) |
| 170 |
| 171 else: |
| 172 print 'No Rows Found' |
| 173 |
| 174 |
| 175 if __name__ == '__main__': |
| 176 main(sys.argv) |
OLD | NEW |