Skip to content

Instantly share code, notes, and snippets.

@lgzarturo
Created March 2, 2022 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgzarturo/128fffbf5457e36da5d10595e1774fb9 to your computer and use it in GitHub Desktop.
Save lgzarturo/128fffbf5457e36da5d10595e1774fb9 to your computer and use it in GitHub Desktop.
import json
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials
def get_service_using_client_id(api_name, api_version, scopes, key_file_location):
credentials = Credentials.from_service_account_info(key_file_location, scopes=scopes)
service = build(api_name, api_version, credentials=credentials)
return service
def get_account_summaries(service):
accounts = service.management().accountSummaries().list().execute()
for account in accounts.get('items', []):
print_property_summaries(account)
def print_property_summaries(account_summary):
if account_summary:
for property in account_summary.get('webProperties', []):
print('%s, %s, %s' % (account_summary.get('name'), property.get('websiteUrl'), property.get('id')))
# print_profile_summary(property)
def print_profile_summary(property_summary):
if property_summary:
for profile in property_summary.get('profiles', []):
print(' %s (%s) | %s' % (profile.get('name'), profile.get('id'),
profile.get('type')))
def get_first_profile_id(service):
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
account = accounts.get('items')[0].get('id')
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
property = properties.get('items')[0].get('id')
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_results(service, profile_id):
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
if results:
print('View (Profile):', results.get('profileInfo').get('profileName'))
print('Total Sessions:', results.get('rows')[0][0])
else:
print('No results found')
def main():
scope = 'https://www.googleapis.com/auth/analytics.readonly'
key_file_location = 'hotels-network-2609a377e6b7.json'
service_account_info = json.load(open(key_file_location))
service = get_service_using_client_id(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=service_account_info)
get_account_summaries(service)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment