GA Multi Channel Funnels Reporting Python errors - python

I have successfully be able to query data from Google Analytics with the python exemple available on G web site using reports().batchGet()
Now I have to do the same with the multi channel funnel (mcf).
Everything I can see on StackO or anywhere else is to call service.data().mcf().get(). But then I got the error AttributeError: 'Resource' object has no attribute 'service'.
I think it's the way I build my request but using the google apiclient the same way I did before I don't know what I have wrong.
Here a sample of the way I init this call :
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'client_secrets.json'
def initialize_analytics_reporting():
"""
Initializes an Analytics Reporting API V4 service object.
:return: 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, next_token):
"""
Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns:
The Analytics Reporting API V4 response.
"""
print(analytics.__dict__)
if next_token == 0:
return analytics.data.mcf().get(..)
[...]
NOT FOR FUTUR ME OR OTHER :
analytics = build('analytics', 'v3', credentials=credentials)
Working!

You can pull data using below code:
def initialize_mcf_analyticsreporting():
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
analytics = build('analytics', 'v3', credentials=credentials)
mcf_service = analytics.data().mcf()
return mcf_service
mcf_service = initialize_mcf_analyticsreporting()
report = mcf_service.get(
start_date=start_date,
end_date=end_date,
metrics='mcf:totalConversions,mcf:totalConversionValue',
ids='ga:xxxxxxx', #Your View ID to replaced by xxxxxxx
dimensions="mcf:sourceMediumPath,mcf:campaignPath",
max_results=10000
).execute()
You may refer to Google's Documentation here https://developers.google.com/analytics/devguides/reporting/mcf/v3/mcfDevGuide
for additional information.

Related

Inserting Custom Dimensions using Google Analytics API v3

I am using Google Analytics API to insert a custom dimension. I have set up the required Oauth2 credentials and obtained an access token and a refresh token. However, when I called my function that inserts a custom dimension to a specified Account and webProperty in Google Analytics, I get an error message that reads as follows:
<HttpError 403 when requesting: URL
returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">
I opened the URL and got the following error message
Error message
Using the same code, I am able to fetch all accounts and webProperties in Google Analytics but apparently it can neither insert nor update custom dimensions and I don't know what I am missing in my code.
Here is my code:
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.errors import HttpError
import os
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
scope = ['https://www.googleapis.com/auth/analytics']
def get_service():
"""
authorises user to access GA resources and builds a service object
"""
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', scopes=scope)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json', scopes=scope)
creds = flow.run_local_server(port=80)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
# build a service object
service = build('analytics', 'v3', credentials=creds)
return service
def insert_customDimension(service):
# Inserts a custom Dimension at a specific index.
try:
service.management().customDimensions().insert(
accountId=ACCOUNT_ID,
webPropertyId=WEB_PROPERTY_ID,
body={'name': 'free to use',
'scope': 'HIT',
'active': False,
'index': 200
}
).execute()
except HttpError as error:
print(error)
except TypeError as er:
print(er)
def main():
# Authenticate and construct service.
service = get_service()
insert_customDimension(service)
if __name__ == '__main__':
main()
I would like to understand what am I doing wrong or what do I need to change in my code? I have deleted the token.json file and ran the code but I was unable to complete the authorization flow and not token.json was automatically created. I manually obtained the refresh and access token and created the file. I have admin privileges to the Google Analytics account I am trying to insert custom dimensions into.

How to authorize a Google APIs without user interaction?

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?
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
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.

Using Google OAuth2 with Analytics Reporting to serve user data Python

I am trying to setup a google analytics reporting tool, but would like to use the OAuth2 client to allow users to log in with a 'log in with google' button in order to view their data.
I am using the quick start guide from Analytics V4 Reporting which gives a file with the below content:
"""A simple example of how to access the Google Analytics API."""
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
def get_service(api_name, api_version, scopes, key_file_location):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scopes: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scopes)
# Build the service object.
service = build(api_name, api_version, credentials=credentials)
return service
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
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):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions within the past seven days.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
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():
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/analytics.readonly'
key_file_location = '<REPLACE_WITH_JSON_FILE>'
# Authenticate and construct service.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
profile_id = get_first_profile_id(service)
print_results(get_results(service, profile_id))
if __name__ == '__main__':
main()
This has a function that gets service account info from a hard-coded json file:
ServiceAccountCredentials.from_json_keyfile_name(key_file_location, scopes=scopes)
And then uses that info to get info using the hard-coded file.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
This is fine if I want just my own data, but how do I go about retrieving the information (analytics data, scopes, view ID etc) using a simple authentication in python? I haven't been able to stitch the documentation for OAuth2 together for this use case.
If anyone could help me, or point me to a resource I could use that would be great.
Thanks.

Multi-Channel Funnel API - Unknown API or Version

I want to get MCF data using an API, however getting an error:
googleapiclient.errors.UnknownApiNameOrVersion: name: analyticsmultichannelfunnel version: v4
I am using the following code to connect:
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
print("test")
analytics = build('mcf', 'v4', credentials=credentials)
print(analytics)
return analytics
any idea how I can solve it? Or where I can find a sample code for using MCF API in Python?
The MCF API does not have a v4; see the latest documentation for v3

Google Analytics fetch view I'd using API

I'm trying to build a support analytics tool which will let the end-user to create a dashboard of his own using data from multiple sources, one such source is Google Analytics. I used Google Analytics Core reporting API to fetch the data. However as of now, I'm manually inserting the view I'd of my user account to fetch the data. Since I'm building it for end users, I need to be able to programmatically(using API) to fetch the view i'd of a user account when they are authorizing my app using oauth. I have seen tools like databox which have achieved this so wondering how to replicate the same. Here's the code snippet I'm using
import argparse
from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = 'xxxxxx' #manually inserted view I'd here
def initialize_analyticsreporting():
"""Initializes the analyticsreporting service object.
Returns:
analytics an authorized analyticsreporting service object.
"""
# Parse command-line arguments.
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args([])
# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(
CLIENT_SECRETS_PATH, scope=SCOPES,
message=tools.message_if_missing(CLIENT_SECRETS_PATH))
# Prepare credentials, and authorize HTTP object with them.
# If the credentials don't exist or are invalid run through the native client
# flow. The Storage object will ensure that if successful the good
# credentials will get written back to a file.
storage = file.Storage('analyticsreporting.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
# Build the service object.
analytics = build('analyticsreporting', 'v4', http=http)
return analytics
def get_report(analytics):
# Use the Analytics Service Object to query the Analytics Reporting API V4.
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}]
}]
}
).execute()
def print_response(response):
"""Parses and prints the 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', [])
rows = report.get('data', {}).get('rows', [])
for row in 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()
I figured out the answer myself. We have to use Management API to fetch all View Id's of a particular account and pass that as a parameter to core reporting api for getting the metrics/dimensions.

Categories