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