Matt Menzenski
12/13/2022, 5:01 AMfrom apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import json
SCOPES = [
'<https://www.googleapis.com/auth/analytics.readonly>'
]
KEY_FILE_LOCATION = 'src/client_secrets.json'
VIEW_ID = '<my view ID>'
def initialize_analyticsreporting():
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION,
SCOPES
)
return build('analyticsreporting', 'v4', credentials=credentials)
def get_report(analytics):
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges': [
{
'startDate': '3daysAgo',
'endDate': 'today',
},
],
'metrics': [
{ 'expression': 'ga:users', },
{ 'expression': 'ga:newUsers', },
],
'dimensions': [
{ 'name': 'ga:date', },
],
},
{
'viewId': VIEW_ID,
'dateRanges': [
{
'startDate': '3daysAgo',
'endDate': 'today',
},
],
'metrics': [
{ 'expression': 'ga:sessions', },
{ 'expression': 'ga:sessionsPerUser', },
{ 'expression': 'ga:avgSessionDuration', },
],
'dimensions': [
{ 'name': 'ga:date', },
{ 'name': 'ga:country', },
],
},
],
}
).execute()
def print_response(response):
print(json.dumps(response, indent=2))
if __name__ == '__main__':
analytics = initialize_analyticsreporting()
response = get_report(analytics)
print_response(response)