Reputation: 11
I am trying to run automated daily API calls to Google Analytics API
The problem is that when I run the command to establish the connection, a window pops up in my browser where I have to click to allow the access to my project.
Is there any was to dodge this step, since this step requires a visual interface and action in my browser I cannot seem to automate it to run in the background daily.
Any suggestions?
Upvotes: 1
Views: 496
Reputation: 116888
You should look into using a service account. Service accounts are like dummy users, you can preauthorize the service account access to your Google analytics account by taking the service account email address and adding it as a user on the account you wish to access. By doing this the code will not need to be authorized by a user as you are seeing currently.
Service accounts should only be used on accounts that you the developer own, it shouldn't be used to access another user's account, for that you should be using Oauth2.
The official tutorial can be found here Hello Analytics Reporting API v4; Python quickstart for service accounts
"""Hello Analytics Reporting API V4."""
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'
def initialize_analyticsreporting():
"""Initializes an Analytics Reporting API V4 service object.
Returns:
An authorized Analytics Reporting API V4 service object.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
# Build the service object.
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
def get_report(analytics):
"""Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns:
The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:country'}]
}]
}
).execute()
def print_response(response):
"""Parses and prints the Analytics Reporting API V4 response.
Args:
response: An Analytics Reporting API V4 response.
"""
for report in response.get('reports', []):
columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
for row in report.get('data', {}).get('rows', []):
dimensions = row.get('dimensions', [])
dateRangeValues = row.get('metrics', [])
for header, dimension in zip(dimensionHeaders, dimensions):
print(header + ': ', dimension)
for i, values in enumerate(dateRangeValues):
print('Date range:', str(i))
for metricHeader, value in zip(metricHeaders, values.get('values')):
print(metricHeader.get('name') + ':', value)
def main():
analytics = initialize_analyticsreporting()
response = get_report(analytics)
print_response(response)
if __name__ == '__main__':
main()
You will need to create Service account credentials on Google developer console the credentials you are using now will not work. Here is a video on How to create Google Oauth2 Service account credentials.
Remember to enable the Google analytics Reporting api under libraries.
Upvotes: 1
Reputation: 5198
You need to go into the google cloud console, enable the API, and set up a service account with the proper keys. https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py
Upvotes: 1