Multi-Channel Funnel API - Unknown API or Version - python

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

Related

Consult chat reports using admin sdk google workspace

I'm new to integrations with the API SDK GOOGLE, and I need to consume the Workspace activity reports regarding the use of google Chat, I configured the following code, but I believe it is wrong, I didn't find a documentation that helps me to validate the form correct way to make calls to the reports api
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
import googleapiclient.discovery
#escopos necessarios
scopes = [
'https://www.googleapis.com/auth/admin.reports.usage.readonly',
'https://www.googleapis.com/auth/drive.metadata.readonly',
'https://www.googleapis.com/auth/admin.reports.usage.readonly',
'https://www.googleapis.com/auth/admin.reports.audit.readonly',
'https://www.googleapis.com/auth/analytics',
'https://www.googleapis.com/auth/analytics.readonly',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/apps.alerts',
'https://www.googleapis.com/auth/apps.order.readonly',
'https://www.googleapis.com/auth/apps.order',
'https://www.googleapis.com/auth/admin.directory.user.readonly',
'https://www.googleapis.com/auth/admin.directory.domain',
'https://www.googleapis.com/auth/admin.directory.domain.readonly',
'https://www.googleapis.com/auth/calendar.readonly' ,
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/cloud-platform'
]
#dominio que sera pesquisado
TARGET='dominio.test.com'
#credenciais de acesso
credentials = ServiceAccountCredentials.from_json_keyfile_name('./chave.json', scopes)
delegated_credentials = credentials.create_delegated('admin#email.com')
http_auth = credentials.authorize(Http())
service = googleapiclient.discovery.build('admin', 'directory_v1',
credentials=delegated_credentials)
response = service.activities().list(users='all',applicationName='chat')
print(response)
I've already used this code for other queries and it's working for accessing the directory and listing users but when I tried to adapt it to query chat activities it doesn't work I have the following error
response = service.activities().list(customerId='all',applicationName='chat')
AttributeError: 'Resource' object has no attribute 'activities'

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.

GA Multi Channel Funnels Reporting Python errors

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.

Google Sheets API json files - What is the difference between CLIENT_SECRET and oauth2client credentials?

I followed the Google Sheet Python API Quickstart guide (https://developers.google.com/sheets/api/quickstart/python) and was able to get it working using their supplied code:
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'my/path/client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
credential_path = 'my/path/sheets.googleapis.com-python-quickstart.json'
store = Storage(credential_path)
credentials = store.get()
## !!!!! Is this needed?
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
In the default setup I downloaded two JSON files:
client_secret.JSON
downloaded to project directory.
sheets.googleapis.com-python-quickstart.JSON
downloaded to ~/.credentials directory
The sheets.googleapis.com JSON file starts with:
"_module": "oauth2client.client".
Question 1: What is the purpose for each of these JSON files?
Question 2: Are both of these JSON files needed to successfully use the Google Sheets API?
I am thinking no, as I am able to get the API working without the client_secret.JSON file.
How about this answer? I think when you know the OAuth2 process for retrieving access token and refresh token, you can understand the meaning of both files. The flow for retrieving access token and refresh token using OAuth2 is as follows.
Flow :
Download client_secret.JSON from the API Console.
client_secret.JSON includes client_id, client_secret and redirect_uris.
Retrieve an authorization code using scopes and client_id from client_secret.JSON.
Retrieve access token and refresh token using the authorization code, client_id, client_secret and redirect_uris.
Retrieved access token, refresh token and other parameters are saved to the file of sheets.googleapis.com-python-quickstart.JSON.
Note :
When you run the Quickstart for the first time, the authorization process using your browser is launched. At that time, the script of Quickstart retrieves the authorization code using client_id and scopes, and then the access token and refresh token are retrieved using the authorization code, client_id, client_secret and redirect_uris.
After the first run of the Quickstart, the access token is retrieved by the refresh token from sheets.googleapis.com-python-quickstart.JSON. By this, retrieving the authorization code using browser is not required to do. So when there is sheets.googleapis.com-python-quickstart.JSON, client_secret.JSON is not required.
I think that this leads to an answer for your Question 2.
But, if you want to change scopes and/or credentials of client_secret.JSON, the authorization process using browser and retrieving the authorization code are required to do. For this, you have to remove sheets.googleapis.com-python-quickstart.JSON and authorize again. At that time, at Quickstart, client_secret.JSON is used again.
References :
Using OAuth 2.0 to Access Google APIs
Authorization for Google Services
If this is not useful for you, I'm sorry.

Google spreadsheets api do not use OAuth2?

I'm trying to make authorized requests to the google spreadsheets API and all the examples I found requests email and password from the user.
http://www.payne.org/index.php/Reading_Google_Spreadsheets_in_Python
http://www.mattcutts.com/blog/write-google-spreadsheet-from-python/
http://mrwoof.tumblr.com/post/1004514567/using-google-python-api-to-get-rows-from-a-google
Well this problem was solved with OAuth2 protocol which Google implements. I've gone through the OAuth2 process and I have a valid access_token, which I use to interact with Google Drive smoothly:
access_token = get_access_token() # external function
user_agent = request.META['HTTP_USER_AGENT']
credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('drive', 'v2', http)
service.files().copy(fileId=k, body=dict(title="Copia")).execute() # this works!
But I can't figure out a way to use the access_token to interact with the spreadsheets API. Does it still uses email and password login?
Thanks!
PS: BTW, I'm using the python gdata package, and please let me know if you have a good reference for it! :)
So, if you already have an access token (maybe you got it by your own via Oauth2 protocol, like me). You can interact with google spreadsheet api passing an instance of AuthSubToken to methods of SpreadsheetsClient.
from gdata.gauth import AuthSubToken
from gdata.spreadsheets.client import SpreadsheetsClient
atok = AuthSubToken(token_string=get_access_token()) # acess token via protocol
data = SpreadsheetsClient().get_worksheets(key, auth_token=atok)

Categories