API de Hello Analytics: Guía de inicio rápido de Python para aplicaciones instaladas

En este instructivo, se explican los pasos necesarios para acceder a una cuenta de Google Analytics, consultar las APIs de Analytics, manejar las respuestas de la API y generar los resultados. En este instructivo, se usan la API de Core Reporting v3.0, la API de Management v3.0 y OAuth2.0.

Paso 1: Habilita la API de Analytics

Para comenzar a usar la API de Google Analytics, primero debes utilizar la herramienta de configuración, que te guiará para crear un proyecto en la Consola de APIs de Google, habilitar la API y crear credenciales.

Crea un ID de cliente

En la página Credenciales, haz lo siguiente:

  1. Haz clic en Crear credenciales y selecciona ID de cliente de OAuth.
  2. En TIPO DE APLICACIÓN, selecciona Otro.
  3. Asigna un nombre a la credencial.
  4. Haz clic en Crear.

Selecciona la credencial que acabas de crear y haz clic en Descargar JSON. Guarda el archivo descargado como client_secrets.json; lo necesitarás más adelante en el instructivo.

Paso 2: Instala la biblioteca cliente de Google

Puedes usar un administrador de paquetes o descargar una biblioteca cliente de Python para instalarla de forma manual:

pip

Usa pip, la herramienta recomendada para instalar paquetes de Python:

sudo pip install --upgrade google-api-python-client

Herramientas de configuración

Usa la herramienta easy_install que se incluye en el paquete setuptools:

sudo easy_install --upgrade google-api-python-client

Instalación manual

Descarga la biblioteca cliente para Python más reciente, descomprime el código y ejecuta lo siguiente:

sudo python setup.py install

Es posible que debas invocar el comando con privilegios de superusuario (sudo) para realizar la instalación en el sistema Python.

Paso 3: Configura la muestra

Deberás crear un solo archivo llamado HelloAnalytics.py, que contendrá el código de muestra proporcionado.

  1. Copia o descarga el siguiente código fuente en HelloAnalytics.py.
  2. Mueve el client_secrets.json descargado previamente dentro del mismo directorio que el código de muestra.
"""A simple example of how to access the Google Analytics API."""

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


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')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
        accountId=account).execute()

    if properties.get('items'):
      # Get the first property id.
      property = properties.get('items')[0].get('id')

      # Get a list of all views (profiles) for the first property.
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).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
  # for the number of sessions in the past seven days.
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:sessions').execute()


def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
    print 'Total Sessions: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'


def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, 'client_secrets.json')
  profile = get_first_profile_id(service)
  print_results(get_results(service, profile))


if __name__ == '__main__':
  main()

Paso 4: Ejecuta la muestra

Después de habilitar la API de Analytics, instala la biblioteca cliente de las APIs de Google para Python y configura el código fuente de muestra que la muestra está lista para ejecutarse.

Ejecuta la muestra con el comando siguiente:

python HelloAnalytics.py
  1. La aplicación cargará la página de autorización en un navegador.
  2. Si aún no accediste a tu Cuenta de Google, se te pedirá que lo hagas. Si accediste a varias Cuentas de Google, se te pedirá que selecciones una cuenta para usar en la autorización.

Cuando termines estos pasos, la muestra mostrará el nombre de la primera vista (perfil) de Google Analytics del usuario autorizado y la cantidad de sesiones de los últimos siete días.

Con el objeto de servicio autorizado de Analytics, ahora puedes ejecutar cualquiera de las muestras de código que se encuentran en los documentos de referencia de la API de Management. Por ejemplo, podrías intentar cambiar el código para usar el método accountSummaries.list.

Solución de problemas

AttributeError: el objeto 'Module_six_moves_urllib_parse' no tiene el atributo 'urlparse'

Este error puede ocurrir en Mac OS X, donde la instalación predeterminada del módulo "seis" (una dependencia de esta biblioteca) se carga antes de la que instaló pip. Para solucionar el problema, agrega la ubicación de instalación de pip a la variable de entorno del sistema PYTHONPATH:

  1. Determina la ubicación de instalación de pip con el siguiente comando:

    pip show six | grep "Location:" | cut -d " " -f2
    

  2. Agrega la siguiente línea a tu archivo ~/.bashrc y reemplaza <pip_install_path> por el valor determinado anteriormente:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. Vuelve a cargar tu archivo ~/.bashrc en cualquier ventana de terminal abierta con el siguiente comando:

    source ~/.bashrc