Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top