Skip to content

Commit ba28abe

Browse files
author
api.nickm@google.com
committed
Adding v2 client library support for Google Analytics API
1 parent 220fb38 commit ba28abe

8 files changed

Lines changed: 1018 additions & 12 deletions

File tree

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#!/usr/bin/python
2+
#
3+
# Copyright 2009 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Sample Google Analytics Data Export API Account Feed application.
18+
19+
This sample demonstrates how to retrieve the important data from the Google
20+
Analytics Data Export API Account feed using the Python Client library. This
21+
requires a Google Analytics username and password and uses the Client Login
22+
authorization routine.
23+
24+
Class AccountFeedDemo: Prints all the import Account Feed data.
25+
"""
26+
27+
__author__ = 'api.nickm@google.com (Nick Mihailovski)'
28+
29+
30+
import gdata.analytics.client
31+
import gdata.sample_util
32+
33+
def main():
34+
"""Main fucntion for the sample."""
35+
36+
demo = AccountFeedDemo()
37+
demo.PrintFeedDetails()
38+
demo.PrintAccountEntries()
39+
40+
41+
class AccountFeedDemo(object):
42+
"""Prints the Google Analytics account feed
43+
44+
Attributes:
45+
account_feed: Google Analytics AccountList returned form the API.
46+
"""
47+
48+
def __init__(self):
49+
"""Inits AccountFeedDemo."""
50+
51+
SOURCE_APP_NAME = 'Google-accountFeedDemoPython-v1'
52+
my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME)
53+
54+
try:
55+
gdata.sample_util.authorize_client(
56+
my_client,
57+
service=my_client.auth_service,
58+
source=SOURCE_APP_NAME,
59+
scopes=['https://www.google.com/analytics/feeds/'])
60+
except gdata.client.BadAuthentication:
61+
exit('Invalid user credentials given.')
62+
except gdata.client.Error:
63+
exit('Login Error')
64+
65+
account_query = gdata.analytics.client.AccountFeedQuery()
66+
self.feed = my_client.GetAccountFeed(account_query)
67+
68+
def PrintFeedDetails(self):
69+
"""Prints important Analytics related data found at the top of the feed."""
70+
71+
print 'Feed Title = ' + self.feed.title.text
72+
print 'Feed Id = ' + self.feed.id.text
73+
print 'Total Results Found = ' + self.feed.total_results.text
74+
print 'Start Index = ' + self.feed.start_index.text
75+
print 'Results Returned = ' + self.feed.items_per_page.text
76+
77+
def PrintAccountEntries(self):
78+
"""Prints important Analytics data found in each entry"""
79+
80+
for entry in self.feed.entry:
81+
print '--------------------------'
82+
print 'Profile Name = ' + entry.title.text
83+
print 'Table ID = ' + entry.table_id.text
84+
print 'Account Name = ' + entry.GetProperty('ga:accountId').value
85+
print 'Profile ID = ' + entry.GetProperty('ga:accountName').value
86+
print 'Web Property ID = ' + entry.GetProperty('ga:webPropertyId').value
87+
print 'Profile Currency = ' + entry.GetProperty('ga:currency').value
88+
print 'Profile TimeZone = ' + entry.GetProperty('ga:timezone').value
89+
90+
91+
if __name__ == '__main__':
92+
main()
93+
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
#!/usr/bin/python
2+
#
3+
# Copyright 2009 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Sample Google Analytics Data Export API Data Feed application.
18+
19+
This sample demonstrates how to make requests and retrieve the important
20+
information from the Google Analytics Data Export API Data Feed. This
21+
sample requires a Google Analytics username and password and uses the
22+
Client Login authorization routine.
23+
24+
Class DataFeedDemo: Prints all the important Data Feed informantion.
25+
"""
26+
27+
__author__ = 'api.nickm@google.com (Nick Mihailovski)'
28+
29+
30+
import gdata.analytics.client
31+
import gdata.sample_util
32+
33+
def main():
34+
"""Main function for the sample."""
35+
36+
demo = DataFeedDemo()
37+
demo.PrintFeedDetails()
38+
demo.PrintDataSources()
39+
demo.PrintFeedAggregates()
40+
demo.PrintOneEntry()
41+
demo.PrintFeedTable()
42+
43+
44+
class DataFeedDemo(object):
45+
"""Gets data from the Data Feed.
46+
47+
Attributes:
48+
data_feed: Google Analytics AccountList returned form the API.
49+
"""
50+
51+
def __init__(self):
52+
"""Inits DataFeedDemo."""
53+
54+
SOURCE_APP_NAME = 'Google-dataFeedDemoPython-v1'
55+
my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME)
56+
57+
try:
58+
gdata.sample_util.authorize_client(
59+
my_client,
60+
service=my_client.auth_service,
61+
source=SOURCE_APP_NAME,
62+
scopes=['https://www.google.com/analytics/feeds/'])
63+
except gdata.client.BadAuthentication:
64+
exit('Invalid user credentials given.')
65+
except gdata.client.Error:
66+
exit('Login Error')
67+
68+
table_id = gdata.sample_util.get_param(
69+
name='table_id',
70+
prompt='Please enter your Google Analytics Table id (format ga:xxxx)')
71+
72+
# DataFeedQuery simplifies constructing API queries and uri encodes params.
73+
data_query = gdata.analytics.client.DataFeedQuery({
74+
'ids': table_id,
75+
'start-date': '2008-10-01',
76+
'end-date': '2008-10-30',
77+
'dimensions': 'ga:source,ga:medium',
78+
'metrics': 'ga:visits',
79+
'sort': '-ga:visits',
80+
'filters': 'ga:medium==referral',
81+
'max-results': '50'})
82+
83+
self.feed = my_client.GetDataFeed(data_query)
84+
85+
def PrintFeedDetails(self):
86+
"""Prints important Analytics related data found at the top of the feed."""
87+
88+
print '\n-------- Feed Data --------'
89+
print 'Feed Title = ' + self.feed.title.text
90+
print 'Feed Id = ' + self.feed.id.text
91+
print 'Total Results Found = ' + self.feed.total_results.text
92+
print 'Start Index = ' + self.feed.start_index.text
93+
print 'Results Returned = ' + self.feed.items_per_page.text
94+
print 'Start Date = ' + self.feed.start_date.text
95+
print 'End Date = ' + self.feed.end_date.text
96+
97+
def PrintDataSources(self):
98+
"""Prints data found in the data source elements.
99+
100+
This data has information about the Google Analytics account the referenced
101+
table ID belongs to. Note there is currently exactly one data source in
102+
the data feed.
103+
"""
104+
105+
data_source = self.feed.data_source[0]
106+
107+
print '\n-------- Data Source Data --------'
108+
print 'Table ID = ' + data_source.table_id.text
109+
print 'Table Name = ' + data_source.table_name.text
110+
print 'Web Property Id = ' + data_source.GetProperty('ga:webPropertyId').value
111+
print 'Profile Id = ' + data_source.GetProperty('ga:profileId').value
112+
print 'Account Name = ' + data_source.GetProperty('ga:accountName').value
113+
114+
def PrintFeedAggregates(self):
115+
"""Prints data found in the aggregates elements.
116+
117+
This contains the sum of all the metrics defined in the query across. This
118+
sum spans all the rows matched in the feed.total_results property and not
119+
just the rows returned by the response.
120+
"""
121+
122+
aggregates = self.feed.aggregates
123+
124+
print '\n-------- Metric Aggregates --------'
125+
for met in aggregates.metric:
126+
print ''
127+
print 'Metric Name = ' + met.name
128+
print 'Metric Value = ' + met.value
129+
print 'Metric Type = ' + met.type
130+
print 'Metric CI = ' + met.confidence_interval
131+
132+
def PrintOneEntry(self):
133+
"""Prints all the important Google Analytics data found in an entry"""
134+
135+
print '\n-------- One Entry --------'
136+
if len(self.feed.entry) == 0:
137+
print 'No entries found'
138+
return
139+
140+
entry = self.feed.entry[0]
141+
print 'ID = ' + entry.id.text
142+
143+
for dim in entry.dimension:
144+
print 'Dimension Name = ' + dim.name
145+
print 'Dimension Value = ' + dim.value
146+
147+
for met in entry.metric:
148+
print 'Metric Name = ' + met.name
149+
print 'Metric Value = ' + met.value
150+
print 'Metric Type = ' + met.type
151+
print 'Metric CI = ' + met.confidence_interval
152+
153+
def PrintFeedTable(self):
154+
"""Prints all the entries as a table."""
155+
156+
print '\n-------- All Entries In a Table --------'
157+
for entry in self.feed.entry:
158+
for dim in entry.dimension:
159+
print ('Dimension Name = %s \t Dimension Value = %s'
160+
% (dim.name, dim.value))
161+
for met in entry.metric:
162+
print ('Metric Name = %s \t Metric Value = %s'
163+
% (dim.name, dim.value))
164+
print '---'
165+
166+
167+
if __name__ == '__main__':
168+
main()
169+

src/gdata/analytics/client.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
#!/usr/bin/python
2+
#
3+
# Copyright 2009 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""AnalyticsClient extends gdata.client.GDClient to streamline
18+
Google Analytics Data Export API calls."""
19+
20+
__author__ = 'api.nickm@google.com (Nick Mihailovski)'
21+
22+
23+
import atom.data
24+
import gdata.client
25+
import gdata.analytics.data
26+
27+
28+
class AnalyticsClient(gdata.client.GDClient):
29+
"""Client extension for the Google Analytics API service."""
30+
31+
api_version = '1'
32+
auth_service = 'analytics'
33+
auth_scopes = ['https://www.google.com/analytics/feeds']
34+
account_type = 'GOOGLE'
35+
36+
def __init__(self, auth_token=None, **kwargs):
37+
"""Constructs a new client for the Sites API.
38+
39+
Args:
40+
auth_token: gdata.gauth.ClientLoginToken, AuthSubToken, or
41+
OAuthToken (optional) Authorizes this client to edit the user's data.
42+
kwargs: The other parameters to pass to gdata.client.GDClient
43+
constructor.
44+
"""
45+
46+
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
47+
48+
def get_account_feed(self, feed_uri, auth_token=None, **kwargs):
49+
"""Makes a request to the Analytics API Account Feed.
50+
51+
Args:
52+
feed_uri: str or gdata.analytics.AccountFeedQuery The Analytics Account
53+
Feed uri to define what data to retrieve from the API. Can also be
54+
used with a gdata.analytics.AccountFeedQuery object.
55+
"""
56+
57+
return self.get_feed(feed_uri,
58+
desired_class=gdata.analytics.data.AccountFeed,
59+
auth_token=auth_token,
60+
**kwargs)
61+
62+
GetAccountFeed = get_account_feed
63+
64+
def get_data_feed(self, feed_uri, auth_token=None, **kwargs):
65+
"""Makes a request to the Analytics API Data Feed.
66+
67+
Args:
68+
feed_uri: str or gdata.analytics.AccountFeedQuery The Analytics Data
69+
Feed uri to define what data to retrieve from the API. Can also be
70+
used with a gdata.analytics.AccountFeedQuery object.
71+
"""
72+
73+
return self.get_feed(feed_uri,
74+
desired_class=gdata.analytics.data.DataFeed,
75+
auth_token=auth_token,
76+
**kwargs)
77+
78+
GetDataFeed = get_data_feed
79+
80+
81+
class AccountFeedQuery(gdata.client.GDQuery):
82+
"""Account Feed query class to simplify constructing Account Feed Urls.
83+
84+
To use this class, you can either pass a dict in the constructor that has
85+
all the data feed query parameters as keys.
86+
queryUrl = DataFeedQuery({'max-results': '10000'})
87+
88+
Alternatively you can add new parameters directly to the query object.
89+
queryUrl = DataFeedQuery()
90+
queryUrl.query['max-results'] = '10000'
91+
92+
Args:
93+
query: dict (optional) Contains all the GA Data Feed query parameters
94+
as keys.
95+
"""
96+
97+
scheme = 'https'
98+
host = 'www.google.com'
99+
path = '/analytics/feeds/accounts/default'
100+
101+
def __init__(self, query=None, **kwargs):
102+
self.query = query or {}
103+
gdata.client.GDQuery(self, **kwargs)
104+
105+
106+
class DataFeedQuery(gdata.client.GDQuery):
107+
"""Data Feed query class to simplify constructing Data Feed Urls.
108+
109+
To use this class, you can either pass a dict in the constructor that has
110+
all the data feed query parameters as keys.
111+
queryUrl = DataFeedQuery({'start-date': '2008-10-01'})
112+
113+
Alternatively you can add new parameters directly to the query object.
114+
queryUrl = DataFeedQuery()
115+
queryUrl.query['start-date'] = '2008-10-01'
116+
117+
Args:
118+
query: dict (optional) Contains all the GA Data Feed query parameters
119+
as keys.
120+
"""
121+
122+
scheme = 'https'
123+
host = 'www.google.com'
124+
path = '/analytics/feeds/data'
125+
126+
def __init__(self, query=None, **kwargs):
127+
self.query = query or {}
128+
gdata.client.GDQuery(self, **kwargs)
129+

0 commit comments

Comments
 (0)