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