Search code examples
pythongoogle-cloud-platformgoogle-analyticsgoogle-oauth

Access Google Analytics API without generating service account client_secrets


I am trying to access the Google Analytics report (v4) of a client, so I cannot generate my own client_secrets.json file. In the past I have used the oauth2client library to create a flow and storage object to authenticate via http. Current google documentation still uses the oauth2client library, which according to pypi.org (and google) was deprecated in September of 2018.

Here is the current code we are using to build the service:

import argparse
from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools


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

The current google documentation can be found here: https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/installed-py

How do I create this build without receiving specific client_secrets from the client and without using oauth2client?


Solution

  • If you use the service account flow, all you need to do is ask your client to add an additional user (which is just a api account connection) to their analytics account/property/view that you require access to, and it also means you don't need to construct an oauth2 flow.

    There's step by step instructions of how to set this up and use it with the python library here:

    https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py