I'm looking for the library for this method
analytics.management().accountUserLinks().insert
everytime I try to run it the error is always the same, the method management() doesn't exists into the analytics library.
I've got this from the documentation so I think it should works.
I've tried to download different python libraries without success.
The Google analytics management api. Is part of the Google apis library.
Which means you can use the google-api-python-client
sudo pip install --upgrade google-api-python-client
sample
"""A simple example of how to access the Google Analytics API."""
import argparse
from googleapiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/analytics.manage.users.readonly']
# Service account key file
CREDENTIALS = 'C:\YouTube\dev\credentials.json'
VIEW_ID = '78110423'
def get_service(api_name, api_version, scope, client_secrets_path):
"""Get a service that communicates to a Google API.
Args:
api_name: string The name of the api to connect to.
api_version: string The api version to connect to.
scope: A list of strings representing the auth scopes to authorize for the
connection.
client_secrets_path: string A path to a valid client secrets file.
Returns:
A service that is connected to the specified API.
"""
# 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=scope,
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(api_name + '.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.
service = build(api_name, api_version, http=http)
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 the authorized user.
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
account_links = service.management().accountUserLinks().list(
accountId=account
).execute()
if account_links.get('items', []):
# return the first view (profile) id.
return account_links.get('items', [])
return None
def print_results(results):
print(results)
def main():
# Authenticate and construct service.
service = get_service('analytics', 'v3', SCOPES, CREDENTIALS)
profile = get_first_profile_id(service)
print_results(profile)
if __name__ == '__main__':
main()
Related
I am writing a script that will authenticate to the Gmail API, pull some emails and transform some email data. I can get this working locally since I have the service account file which I am creating a credentials object from and then referencing in the Gmail API, however since this will be running in Google Cloud Product (GCP) the credentials are stored in the environment.
I need to somehow either modify the code to not reference credentials or retrieve a credentials object in the environment.
The code below works locally, however where I am creating the credentials object, I either need to retrieve that from the environment or authenticate in a different way when creating the delegated_credentials and service objects.
from googleapiclient.discovery import build
from google.oauth2 import service_account
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
SERVICE_ACCOUNT_FILE = 'secret.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject('someone#gmail.com')
service = build('gmail', 'v1', credentials=delegated_credentials)
As an example, when using the google cloud storage API, I create the client in GCP as follow:
storage_client = storage.Client()
My scenario: I need to call the Google DBM API using google-api-python-client from a Cloud Function using a service account.
Update
Here the sample code I trying to run:
import google.auth
from googleapiclient.discovery import build
from google.auth.transport import requests
API_NAME = 'doubleclickbidmanager'
API_VERSION = 'v1.1'
SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']
credentials, project_id = google.auth.default(scopes=SCOPES)
print(credentials.service_account_email)
# prints "default"
credentials.refresh(requests.Request())
print(credentials.service_account_email)
# prints "[service-account]#[project].iam.gserviceaccount.com"
service = build(API_NAME, API_VERSION, credentials=credentials)
service.queries().listqueries().execute()
# local: return the queries
# in CF: Encountered 403 Forbidden with reason "insufficientPermissions"
When I run locally setting the environment variable GOOGLE_APPLICATION_CREDENTIALS=keyfile.json works fine.
But when running in the Cloud Function I got the 403 error.
The keyfile.json use the same service account [service-account]#[project].iam.gserviceaccount.com setted in the Cloud Function.
You have to force the library to generate a token to force it to fulfill all its fields. For this, simply call a retry, like this
import google.auth
credentials, project_id = google.auth.default(scopes=SCOPES)
from google.auth.transport import requests
credentials.refresh(requests.Request())
print(credentials._service_account_email)
build(API_NAME, API_VERSION, credentials=credentials)
I'm using a google service account to retrieve the usage of data from different users.
I'm using google's python client to authenticate and retrieve the data.
Code
service = build('drive', 'v3', credentials=auth)
result = service.about().get(email).execute();
result = result.get("storageQuota", {})
I keep getting the following error:
method() takes 1 positional argument but 2 were given
I want to be able to get it from a specific user's drive information using the email as an identifier.
How to get Drive info from yourself
Try this snippet example:
result = service.about().get(fields="*").execute()
result = result.get("storageQuota", {})
print(result)
The print output is:
{'usage': '11638750', 'usageInDrive': '11638750', 'usageInDriveTrash': '7531862'}
How to get Drive info from user in your domain
If you are an admin and want to get users info, do the next steps:
Create project in Admin Console
Create service account
Go to Admin Console > Security > Advanced settings > Manage API client access
In Client Name put the full email of your created Service Account
In One or More API Scopes put https://www.googleapis.com/auth/drive and click Authorize
Come back to Service accounts, select your account, Enable G Suite Domain-wide Delegation
Create Service Account KEY (download it as .json)
Activate Drive API for your project. Go to APIs & Services > Dashboard, click on ENABLE APIS AND SERVICES, search for Drive and Enable it.
Create index.py file with the next code and launch it:
from googleapiclient.discovery import build
from google.oauth2 import service_account
def main():
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'serviceaccountsproject-81ec0d3c1c1c.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
credentials = credentials.with_subject('user#inYourDomain.com')
service = build('drive', 'v3', credentials=credentials)
result = service.about().get(fields="*").execute()
result = result.get("storageQuota", {})
print(result)
if __name__ == '__main__':
main()
And here is an output:
{'usage': '0', 'usageInDrive': '0', 'usageInDriveTrash': '0'}
Reference:
Google Drive API V3 - About - get
Understanding service accounts
The is an undocumented required paramater with that request. Its called fields. I have a bug report out.
service = build('drive', 'v3', credentials=auth)
driveRequest = service.about().get(email);
driveRequest.fields = "*";
result = driveRequest.execute();
result = result.get("storageQuota", {})
Kindly note i am not a python developer this is a guess on how to do it.
I am trying to fetch gsuite alerts via API. I have created a service account as per their docs and I have assigned that service account to my google cloud function.
I do not want to use environment variables or upload credentials along with source code but I want leverage default service account used by function.
from googleapiclient.discovery import build
def get_credentials():
# if one knows credentials file location(when one uploads the json credentials file or specify them in environment variable) one can easily get the credentials by specify the path.
# In case of google cloud functions atleast I couldn't find it the path as the GOOGLE_APPLICATION_CREDENTIALS is empty in python runtime
# the below code work find if one uncomments the below line
#credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location)
credentials = < how to get default credentials object for default service account?>
delegated_credentials = credentials.create_delegated('admin#alertcenter1.bigr.name').create_scoped(SCOPES)
return delegated_credentials
def get_alerts(api_name, api_version, key_file_location=None):
delegated_credentials = get_credentials()
alertcli = build(api_name, api_version, credentials=delegated_credentials)
resp = alertcli.alerts().list(pageToken=None).execute()
print(resp)
Is there any way I can create a default credentials object. I have tried using
from google.auth import credentials but this does not contain create_delegated function and
I have also tried ServiceAccountCredentials() but this requires signer.
Here is an example to use the Gmail API with delegated credentials. The service account credentials will need "Enable G Suite Domain-wide Delegation" enabled.
from google.oauth2 import service_account
from googleapiclient.discovery import build
credentials = service_account.Credentials.from_service_account_file(
credentials_file,
scopes=['https://www.googleapis.com/auth/gmail.send'])
impersonate = 'username#example.com'
credentials = credentials.with_subject(impersonate)
service = build('gmail', 'v1', credentials=credentials)
You can use the google.auth.default function to get the default credentials and use them to make an IAM signer which can be used to create new service account credentials which has the delegated email adress as subject. I have a more detailed answer for a similar question.
There is also Google Cloud Platform Github repository with some documentation about this method.
I have implemented the python-social-auth library for Google OAuth2 in my Django project, and am successfully able to log users in with it. The library stores the access_token received in the response for Google's OAuth2 flow.
My question is: use of the google-api-python-client seems to rely on creating and authorizing a credentials object, then using it to build an API service like so:
...
# send user to Google consent URL, get auth_code in response
credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())
from apiclient.discovery import build
service = build('gmail', 'v1', http=http_auth)
# use service for API calls...
Since I'm starting with an access_token provided by python-social-auth, how do I create & authorize the API client service for future API calls?
Edit: to clarify, the code above is from the examples provided by Google.
Given you already have the OAuth2 access token you can use the AccessTokenCredentials class.
The oauth2client.client.AccessTokenCredentials class is used when you have already obtained an access token by some other means. You can create this object directly without using a Flow object.
Example:
import httplib2
from googleapiclient.discovery import build
from oauth2client.client import AccessTokenCredentials
credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)
You can check examples provided by Google Guide API, for example: sending email via gmail application, https://developers.google.com/gmail/api/guides/sending
If you have an already refreshed latest access token which is not expired, then you can get service variable as:
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
creds = Credentials("<ACCESS_TOKEN>")
service = build('gmail', 'v1', credentials=creds)
# Call the Gmail API