· 6 years ago · Oct 04, 2019, 01:08 PM
1"""A simple example of how to access the Google Analytics API."""
2
3from apiclient.discovery import build
4from oauth2client.service_account import ServiceAccountCredentials
5from urllib2 import HTTPError
6
7
8def get_service(api_name, api_version, scopes, key_file_location):
9 """Get a service that communicates to a Google API.
10
11 Args:
12 api_name: The name of the api to connect to.
13 api_version: The api version to connect to.
14 scopes: A list auth scopes to authorize for the application.
15 key_file_location: The path to a valid service account JSON key file.
16
17 Returns:
18 A service that is connected to the specified API.
19 """
20
21 credentials = ServiceAccountCredentials.from_json_keyfile_name(
22 key_file_location, scopes=scopes)
23
24 # Build the service object.
25 service = build(api_name, api_version, credentials=credentials)
26
27 return service
28
29
30def get_first_profile_id(service):
31 # Use the Analytics service object to get the first profile id.
32
33 # Get a list of all Google Analytics accounts for this user
34 accounts = service.management().accounts().list().execute()
35
36 if accounts.get('items'):
37 # Get the first Google Analytics account.
38 account = accounts.get('items')[0].get('id')
39
40 # Get a list of all the properties for the first account.
41 properties = service.management().webproperties().list(
42 accountId=account).execute()
43
44 if properties.get('items'):
45 # Get the first property id.
46 property = properties.get('items')[0].get('id')
47
48 # Get a list of all views (profiles) for the first property.
49 profiles = service.management().profiles().list(
50 accountId=account,
51 webPropertyId=property).execute()
52
53 if profiles.get('items'):
54 # return the first view (profile) id.
55 return profiles.get('items')[0].get('id')
56
57 return None
58
59
60def get_results(service, profile_id):
61 # Use the Analytics Service Object to query the Core Reporting API
62 # for the number of sessions within the past seven days.
63 return service.data().ga().get(
64 ids='ga:' + profile_id,
65 start_date='7daysAgo',
66 end_date='today',
67 metrics='ga:sessions').execute()
68
69
70def print_results(results):
71 # Print data nicely for the user.
72 if results:
73 print 'View (Profile):', results.get('profileInfo').get('profileName')
74 print 'Total Sessions:', results.get('rows')[0][0]
75
76 else:
77 print 'No results found'
78
79
80def main():
81 # Define the auth scopes to request.
82 scope = 'https://www.googleapis.com/auth/analytics.readonly'
83 key_file_location = 'BW-GA-management-project-877544aa2473.json'
84
85 # Authenticate and construct service.
86 service = get_service(
87 api_name='analytics',
88 api_version='v3',
89 scopes=[scope],
90 key_file_location=key_file_location)
91
92# profile_id = get_first_profile_id(service)
93# print_results(get_results(service, profile_id))
94
95 try:
96 properties = service.management().webproperties().list(
97 accountId='118564295').execute() #Europe T1: 118564295, Segments: 2518866
98
99 except TypeError, error:
100 # Handle errors in constructing a query.
101 print 'There was an error in constructing your query : %s' % error
102
103 except HttpError, error:
104 # Handle API errors.
105 print ('There was an API error : %s : %s' %
106 (error.resp.status, error.resp.reason))
107
108
109 # Example #2:
110 # Retrieves all properties for the user's account, using a
111 # wildcard ~all as the accountId.
112# properties = service.management().webproperties().list(
113# accountId='~all').execute()
114
115
116 # Example #3:
117 # The results of the list method are stored in the webproperties object.
118 # The following code shows how to iterate through them.
119 for property in properties.get('items', []):
120 #print property
121 lst = []
122 try:
123 adWordsLinks = service.management().webPropertyAdWordsLinks().list(accountId='118564295',webPropertyId= property.get('id')).execute()
124
125 except TypeError, error:
126 # Handle errors in constructing a query.
127 print 'There was an error in constructing your query : %s' % error
128
129# except HttpError, error:
130# # Handle API errors.
131# print ('There was an API error : %s : %s' %
132# (error.resp.status, error.resp.reason))
133
134
135 # Example #2:
136 # The results of the list method are stored in the adWordsLinks object.
137 # The following code shows how to iterate through them.
138 for link in adWordsLinks.get('items', []):
139# print 'Link Id = %s' % link.get('id')
140# print 'Link Kind = %s' % link.get('kind')
141# print 'Link Name = %s' % link.get('name')
142
143 # Get the property reference from the entity.
144 property = link.get('entity', {}).get('webPropertyRef', {})
145 #print 'Property Id = %s' % property.get('id')
146# print 'Property Kind = %s' % property.get('kind')
147 #print 'Property Name = %s' % property.get('name')
148# print 'Property Account id = %s' % property.get('accountId')
149
150 # Get the Google Ads accounts.
151 adWordsAccounts = link.get('adWordsAccounts', [])
152
153 for account in adWordsAccounts:
154 lst.append(account.get('customerId'))
155 #print 'Account Id = %s' % account.get('customerId')
156 #print 'Account Kind = %s' % account.get('kind')
157# print 'Auto Tagging Enabled = %s' % account.get('autoTaggingEnabled')
158 for item in lst:
159 print '%s, %s, %s, %s' % (property.get('name'),property.get('id'),property.get('accountId'),item)
160
161
162 #print 'Property Profile Count = %s' % property.get('profileCount')
163 #print 'Property Industry Vertical = %s' % property.get('industryVertical')
164# print 'Property Internal Id = %s' % property.get(
165# 'internalWebPropertyId')
166# print 'Property Level = %s' % property.get('level')
167# if property.get('websiteUrl'):
168# print 'Property URL = %s' % property.get('websiteUrl')
169 #print 'Created = %s' % property.get('created')
170 #print 'Updated = %s' % property.get('updated')
171
172
173if __name__ == '__main__':
174 main()