6

I'm trying to access Google Analytics API using the code provided by their documentation: https://developers.google.com/analytics/solutions/articles/hello-analytics-api

import httplib2
import os

from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run


CLIENT_SECRETS = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'client_secrets.json')
MISSING_CLIENT_SECRETS_MESSAGE = '%s is missing' % CLIENT_SECRETS
FLOW = flow_from_clientsecrets('%s' % CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message=MISSING_CLIENT_SECRETS_MESSAGE,
)
TOKEN_FILE_NAME = os.path.join(os.path.dirname(os.path.abspath(__file__)), '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()
    credentials = prepare_credentials()
    http = credentials.authorize(http)

    return build('analytics', 'v3', http=http)


def get_analytics():
   initialize_service()

But the problem is that this code opens a browser and asks a user to allow access to analytics service. Does anyone know how to access Google Analytics API (=obtain that token) without oauth2?

cansadadeserfeliz
  • 3,033
  • 5
  • 34
  • 50
  • I'm not an expert in google analytics, but [this](http://stackoverflow.com/a/12892625/201359) appears to solve a similar problem. The key insight: "You will indeed have to use a private key instead of an access token" – Óscar López Apr 25 '14 at 22:06
  • @ÓscarLópez thank you for your answer! the difference is that they use an old version of API, that is already closed by Google, and the new one opens a browser window each time I try to access it, moreover it demands me to hace a view for oauth2 callback – cansadadeserfeliz Apr 25 '14 at 22:12
  • Hmmm, then check [this](https://groups.google.com/forum/#!topic/google-analytics-data-export-api/kny9h4YzeHw) thread. Perhaps with [offline access](http://stackoverflow.com/a/9382056/201359)? – Óscar López Apr 25 '14 at 22:17

2 Answers2

4

There are several ways to authorize Google APIs. You are using Web Server mode that allows you to access Google Services on behalf of your client, but what you really want to use in this case are Service Accounts.

First thing make sure the Analytics API Service is enabled for you Cloud Project in the Google Cloud Console.

Then go into Google Cloud Console and create a new Service Account Client ID. This will give you a certificate file and a Service Account Email. That's all you need.

Here's an example of how to authenticate and instantiate the Analytics API.

import httplib2

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Email of the Service Account.
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file.
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def createAnalyticsService():
  f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
      scope='https://www.googleapis.com/auth/analytics.readonly')
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('analytics', 'v3', http=http)

This will access your Google Analytics Account as user SERVICE_ACCOUNT_EMAIL, so you have to go into Google Analytics and give this user access to your Analytics data.

Adapted from: https://developers.google.com/drive/web/service-accounts

Eduardo
  • 22,574
  • 11
  • 76
  • 94
1

As a result I've wrote a blog post with a solution that worked for me:

import httplib2
import os
import datetime

from django.conf import settings

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Email of the Service Account.
SERVICE_ACCOUNT_EMAIL ='12345@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file.
SERVICE_ACCOUNT_PKCS12_FILE_PATH = os.path.join(
    settings.BASE_DIR,
    '53aa9f98bb0f8535c34e5cf59cee0f32de500c82-privatekey.p12',
)


def get_analytics():
    f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
    key = f.read()
    f.close()

    credentials = SignedJwtAssertionCredentials(
        SERVICE_ACCOUNT_EMAIL,
        key,
        scope='https://www.googleapis.com/auth/analytics.readonly',
    )
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build('analytics', 'v3', http=http)

    end_date = datetime.date.today()
    # 30 days ago
    start_date = end_date - datetime.timedelta(days=30)

    data_query = service.data().ga().get(**{
        'ids': 'ga:123456',  # the code of our project in Google Analytics
        'dimensions': 'ga:pageTitle,ga:pagePath',
        'metrics': 'ga:pageviews,ga:uniquePageviews',
        'start_date': start_date.strftime('%Y-%m-%d'),
        'end_date': end_date.strftime('%Y-%m-%d'),
        'sort': '-ga:pageviews',
    })
    analytics_data = data_query.execute()
    return analytics_data
cansadadeserfeliz
  • 3,033
  • 5
  • 34
  • 50