Buy use Google Analytics API (V4) I would like to upload file "Product Data"
This is the sample code from GA Documentation
from apiclient.http import MediaFileUpload
try:
media = MediaFileUpload('custom_data.csv',
mimetype='application/octet-stream',
resumable=False)
daily_upload = analytics.management().uploads().uploadData(
accountId='123456',
webPropertyId='UA-123456-1',
customDataSourceId='9876654321',
media_body=media).execute()
except TypeError, error:
# Handle errors in constructing a query.
print 'There was an error in constructing your query : %s' % error
except HttpError, error:
# Handle API errors.
print ('There was an API error : %s : %s' %
(error.resp.status, error.resp.reason))
This is What I ahve done, but I still have an issue regarding this part - analytics.management().uploads()
import argparse
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from googleapiclient.http import MediaFileUpload
# SET VARS
CUSTOM_DATA_SOURCE_ID='_xxxxxxx'
WEB_PROPERTY_ID='UA-xxxxx-1'
ACCOUNT_ID='xxxxxx'
CSV_IMPORT_FILE_LOCATION='test_file.csv'
CREDENTIALS_KEY_FILE_LOCATION='key.json'
def get_service(api_name, api_version, scope, key_file_location):
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scope)
http = credentials.authorize(httplib2.Http())
# Build the service object.
service = build(api_name, api_version, http=http)
return service
def uploadCSV(service):
try:
media = MediaFileUpload(CSV_IMPORT_FILE_LOCATION,
mimetype='application/octet-stream',
resumable=False)
daily_upload = service.management().uploads().uploadData(
accountId=ACCOUNT_ID,
webPropertyId=WEB_PROPERTY_ID,
customDataSourceId=CUSTOM_DATA_SOURCE_ID,
media_body=media).execute()
except TypeError, error:
# Handle errors in constructing a query.
print 'There was an error in constructing your query : %s' % error
def main():
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.edit','https://www.googleapis.com/auth/analytics']
# Authenticate and construct service.
service = get_service('analytics', 'v4', scope, CREDENTIALS_KEY_FILE_LOCATION)
# Upload CSV Data
uploadCSV(service)
if __name__ == '__main__':
main()
This is an error which I have received all the time:
AttributeError: 'Resource' object has no attribute 'management'
Any suggestions??
I assume that this is because I do not have these methods (management().uploads()) but this is what example from documentation says.
The current analytics api v4 only includes the reporting side of the API. To access the management endpoint you have to use v3. Try to rewrite your code using the v3 version of the API.
Here's what v3 looks like
Here's what v4 looks like
To start change this line:
service = get_service('analytics', 'v3', scope, CREDENTIALS_KEY_FILE_LOCATION)
But it might require more rewriting than this.
Related
I am trying to use the Google Indexing BATCH Requests but it's not working. What am I doing wrong?
Here is my code: There's no proper documentation, So I have modified it myself. However, It's generating errors.
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.http import BatchHttpRequest
import httplib2
from googleapiclient.discovery import build
SCOPES = [ "https://www.googleapis.com/auth/indexing" ]
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"
# service_account_file.json is the private key that you created for your service account.
JSON_KEY_FILE = "service_account_file.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
service = build('indexing', 'v3', credentials=credentials)
def insert_event(request_id, response, exception):
if exception is not None:
print(exception)
else:
print(response)
batch = BatchHttpRequest(callback=insert_event)
batch.add(service.events().quickAdd(url="URL HERE", type="URL_UPDATED"))
batch.add(service.events().quickAdd(url="URL HERE", type="URL_UPDATED"))
batch.execute(http=http)
ERROR:
Traceback (most recent call last):
File "c:\Users\Sofia\Downloads\ss.py", line 23, in <module>
batch.add(service.events.quickAdd(url="https://jobsinwales.org/jobs/united-kingdom-jobs/co-225/", type="URL_UPDATED"))
AttributeError: 'Resource' object has no attribute 'events'
A few references you may find useful:
Here's an explanation of how to batch requests. There's reference material for the python client library at Indexing API reference.
See also Indexing API Quickstart (all the reference docs are dynamically generated from the same place).
Minor updates made to your code:
batch = service.new_batch_http_request(callback=insert_event)
batch.add(service.urlNotifications().publish(
body={"url": "URL HERE", "type": "URL_UPDATED"}))
batch.add(service.urlNotifications().publish(
body={"url": "URL HERE", "type": "URL_UPDATED"}))
batch.execute()
Secondly, though this should work as is, oauth2client is deprecated. You may want to consider upgrading to the google-auth library.
from google.oauth2 import service_account
SCOPES = [ "https://www.googleapis.com/auth/indexing" ]
JSON_KEY_FILE = "service_account_file.json"
credentials = service_account.Credentials.from_service_account_file(
JSON_KEY_FILE, scopes=SCOPES)
I am trying to upload an APK to Google Play using the Developer API. I have a Python script that mostly works, but the upload keeps returning a "HttpError 403 when requesting 'APK size too big'" error. We have had no problems uploading and releasing the app manually through the web interface. Am I missing a setting somewhere?
Here is my current script:
import argparse
from googleapiclient.discovery import build
import google_auth_httplib2
import httplib2
from oauth2client import client
from google.oauth2 import service_account
from google.auth.transport.requests import Request
import sys, os, socket
def main():
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
SCOPES = ['https://www.googleapis.com/auth/androidpublisher']
SERVICE_ACCOUNT_FILE = fullpath + '/authorization_data.json' # access keys json file
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
credentials.refresh(Request())
print(credentials.token)
http = httplib2.Http(timeout=300)
http = google_auth_httplib2.AuthorizedHttp(credentials, http=http)
service = build('androidpublisher', 'v3', http=http)
package_name = 'com.company.app'
apk_file = 'upload/myapp.apk'
try:
print('creating edit')
edit_request = service.edits().insert(body={}, packageName=package_name)
result = edit_request.execute()
edit_id = result['id']
print('id: ' + edit_id)
print('uploading apk')
apk_response = service.edits().apks().upload(
editId=edit_id,
packageName=package_name,
media_body=apk_file
).execute()
print('Version code %d has been uploaded' % apk_response['versionCode'])
print('committing edit')
commit_request = service.edits().commit(
editId=edit_id,
packageName=package_name
).execute()
print('Edit "%s" has been committed' % commit_request['id'])
except client.AccessTokenRefreshError:
print('The credentials have been revoked or expired, please re-run the application to re-authorize')
if __name__ == '__main__':
main()
I try my google API Project
from __future__ import print_function
import httplib2
from oauth2client import tools
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from apiclient import discovery
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for
# installed applications.
#
# Go to the Google API Console, open your application's
# credentials page, and copy the client ID and client secret.
# Then paste them into the following code.
FLOW = OAuth2WebServerFlow(
client_id='592262365202-h6qu4mrf2b043e2gv2qf5grjg0j53ádfasdfsf2s5.apps.googleusercontent.com',
client_secret='VVxrBm9SEádfsf1ONzyX1oIEwSfB2',
scope='https://www.googleapis.com/auth/contacts',
user_agent='contact_cms/YOUR_APPLICATION_VERSION')
# If the Credentials don't exist or are invalid, run through the
# installed application flow. The Storage object will ensure that,
# if successful, the good Credentials will get written back to a
# file.
def get_credentials(FLOW):
storage = Storage('info.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = tools.run_flow(FLOW, storage)
return credentials
# Create an httplib2.Http object to handle our HTTP requests and
# authorize it with our good Credentials.
def get_http(credentials):
http = httplib2.Http()
http = credentials.authorize(http)
return http
# Build a service object for interacting with the API. To get an API key for
# your application, visit the Google API Console
# and look at your application's credentials page.
def print_list_google_contact_with_number_of_contacts(creds, numberofcontact):
# Call the People API
service = build('people', 'v1', credentials=creds)
print('Ban dang in ra ', numberofcontact, ' danh ba')
results = service.people().connections().list(
resourceName='people/me',
pageSize=numberofcontact,
personFields='names,emailAddresses,phoneNumbers,emailAddresses,addresses').execute()
connections = results.get('connections', [])
# for person in connections:
# names = person.get('names', [])
# if names:
# name = names[0].get('displayName')
# print(name)
for person in connections:
names = person.get('names', [])
if names:
name = names[0].get('displayName')
else:
name = None
phoneNumbers = person.get('phoneNumbers', [])
if phoneNumbers:
phoneNumber = phoneNumbers[0].get('value')
else:
phoneNumber = None
Cities = person.get('addresses', [])
if Cities:
City = Cities[0].get('city')
else:
City = None
emails = person.get('emailAddresses', [])
if emails:
email = emails[0].get('value')
else:
email = None
print(f'{name}: {phoneNumber}: {City}: {email}')
def creat_a_google_contact(http):
service = discovery.build('people', 'v1', http=http, discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
service.people().createContact(parent='people/me', body={
"names": [
{
'givenName': "Samkafafsafsafit"
}
],
"phoneNumbers": [
{
'value': "8600086024"
}
],
"emailAddresses": [
{
'value': "samkit5495#gmail.com"
}
]
}).execute()
def main():
creds=get_credentials(FLOW)
http=get_http(creds)
printout=print_list_google_contact_with_number_of_contacts(creds,10)
creat_a_google_contact(http)
return print(printout)
if __name__ == '__main__':
main()
But when i run, have the log
Traceback (most recent call last):
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 116, in <module>
main()
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 113, in main
creat_a_google_contact(http)
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 104, in creat_a_google_contact
'value': "samkit5495#gmail.com"
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/discovery.py", line 840, in method
raise TypeError('Got an unexpected keyword argument "%s"' % name)
TypeError: Got an unexpected keyword argument "parent"
createContact() does not have a parent param. It has been deprecated:
https://developers.google.com/people/api/rest/v1/people/createContact
parent='people/me' is deprecated. Try without that.
I'm trying to get a connection to my gmail inbox via the python API.
I've got a working example for connecting to the directory api to do user maintenance operations that is set up and working nearly identically to this code. So I've been through all the dev console and security setup for my service account user, who has an email box with a test email sitting in it waiting for me to read it with this code. Currently, my issue is that the line:
gmail_service = build('gmail', 'v1', http=http)
throws:
File "./gmail_test.py", line 29, in <module>
gmail_service = build('gmail', 'v1', http=http)
NameError: name 'http' is not defined
Not quite sure what I'm missing as the nearly identical tailored for admin sdk access works great.
anyway, here's the code:
import urllib2
from httplib2 import Http
from googleapiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
client_email = '<private>#developer.gserviceaccount.com'
with open("Unsubscribe Processing.p12") as f:
private_key = f.read()
creds = SignedJwtAssertionCredentials(
client_email,
private_key,
{
'https://www.googleapis.com/auth/gmail.readonly'
},
sub='serviceaccount#ourdomain.com')
auth = creds.authorize(Http())
gmail_service = build('gmail', 'v1', http=http)
results = gmail_service.users().labels().list(userId='serviceaccount#ourdomain.com').execute()
labels = results.get('labels', [])
if not labels:
print 'No labels found.'
else:
print 'Labels:'
for label in labels:
print label['name']
if __name__ == '__main__':
main()
You haven't defined what the variable http is.
From https://developers.google.com/gmail/api/auth/web-server, this seems to be how you create a Gmail service object:
http = httplib2.Http()
http = creds.authorize(http)
gmail_service = build('gmail', 'v1', http=http)
I'm trying to follow the Google Analytics API tutorial given here. I've followed it step by step. Here are my files
client_secrets.json
{
"installed": {
"client_id": "xxxxxxxxxxxxxxx.apps.googleusercontent.com",
"client_secret": "xxxxxxxxxxxxxxxxx",
"redirect_uris": ["http://127.0.0.1:8000/oauth2callback/"],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token"
}
}
hello_analytics_api_v3_auth.py
#!/usr/bin/python
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
CLIENT_SECRETS = 'client_secrets.json'
MISSING_CLIENT_SECRETS_MESSAGE = '%s is missing' % CLIENT_SECRETS
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/analytics.readonly',
message=MISSING_CLIENT_SECRETS_MESSAGE)
TOKEN_FILE_NAME = 'analytics.dat'
def prepare_credentials():
storage = Storage(TOKEN_FILE_NAME)
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run(FLOW, storage)
return credentials
def initialize_service():
http = httplib2.Http()
#Get stored credentials or run the Auth Flow if none are found
credentials = prepare_credentials()
http = credentials.authorize(http)
#Construct and return the authorized Analytics Service Object
return build('analytics', 'v3', http=http)
hello_analytics_api_v3.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# import the Auth Helper class
import hello_analytics_api_v3_auth
from apiclient.errors import HttpError
from oauth2client.client import AccessTokenRefreshError
def main(argv):
# Initialize the Analytics Service Object
service = hello_analytics_api_v3_auth.initialize_service()
try:
# Query APIs, print results
profile_id = get_first_profile_id(service)
if profile_id:
results = get_results(service, profile_id)
print_results(results)
except TypeError, error:
# Handle errors in constructing a query.
print ('There was an error in constructing your query : %s' % error)
except HttpError, error:
# Handle API errors.
print ('Arg, there was an API error : %s : %s' %
(error.resp.status, error._get_reason()))
except AccessTokenRefreshError:
# Handle Auth errors.
print ('The credentials have been revoked or expired, please re-run '
'the application to re-authorize')
def get_first_profile_id(service):
# 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
firstAccountId = accounts.get('items')[0].get('id')
# Get a list of all the Web Properties for the first account
webproperties = service.management().webproperties().list(accountId=firstAccountId).execute()
if webproperties.get('items'):
# Get the first Web Property ID
firstWebpropertyId = webproperties.get('items')[0].get('id')
# Get a list of all Views (Profiles) for the first Web Property of the first Account
profiles = service.management().profiles().list(
accountId=firstAccountId,
webPropertyId=firstWebpropertyId).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
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='2014-01-10',
end_date='2014-09-08',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
if results:
print 'First View (Profile): %s' % results.get('profileInfo').get('profileName')
print 'Total Sessions: %s' % results.get('rows')[0][0]
else:
print 'No results found'
if __name__ == '__main__':
main(sys.argv)
To test the output, I'm running the command using my terminal as
python hello_analytics_api_v3.py
Running this opens the browser which asks me to authenticate my Google Account and after that I get a 400 error
Error: redirect_uri_mismatch
The redirect URI in the request: http://localhost:8080/ did not match
a registered redirect URI.
How did Google get the http://localhost:8000/ as redirect URI? This is what I've specified in my Google Developer Console App
REDIRECT URIS http://127.0.0.1:8000/oauth2callback/
JAVASCRIPT ORIGINS http://127.0.0.1:8000/
In my console, I had set up a Web Application. Instead I had to setup an Installed Application, since I'm accessing this over the terminal.
A more comprehensive tutorial is given here - http://www.marinamele.com/use-google-analytics-api-with-python