Hello Analytics API: Panduan memulai Python untuk aplikasi terinstal

Tutorial ini akan memandu langkah-langkah yang diperlukan untuk mengakses akun Google Analytics, membuat kueri Analytics API, menangani respons API, dan menampilkan hasilnya. Core Reporting API v3.0, Management API v3.0, dan OAuth2.0 digunakan dalam tutorial ini.

Langkah 1: Aktifkan Analytics API

Untuk mulai menggunakan Google Analytics API, Anda harus menggunakan alat penyiapan terlebih dahulu, yang memandu Anda menyelesaikan pembuatan project di Konsol API Google, mengaktifkan API, dan membuat kredensial.

Membuat client ID

Dari halaman Credentials:

  1. Klik Create Credentials, lalu pilih OAuth client ID.
  2. Pilih Other untuk APPLICATION TYPE.
  3. Beri nama kredensial.
  4. Klik Create.

Pilih kredensial yang baru saja Anda buat, lalu klik Download JSON. Simpan file yang didownload sebagai client_secrets.json; Anda akan memerlukannya nanti dalam tutorial.

Langkah 2: Instal Library Klien Google

Anda dapat menggunakan pengelola paket atau mendownload dan menginstal library klien Python secara manual:

pip

Gunakan pip, alat yang direkomendasikan untuk menginstal paket Python:

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

Setuptools

Gunakan alat easy_install yang disertakan dalam paket setuptools:

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

Penginstalan manual

Download library klien untuk python terbaru, ekstrak kodenya, lalu jalankan:

sudo python setup.py install

Anda mungkin perlu memanggil perintah dengan hak istimewa superuser (sudo) untuk menginstal ke sistem Python.

Langkah 3: Siapkan contoh

Anda harus membuat satu file bernama HelloAnalytics.py, yang akan berisi kode contoh yang diberikan.

  1. Salin atau download kode sumber berikut ke HelloAnalytics.py.
  2. Pindahkan client_secrets.json yang telah didownload sebelumnya ke dalam direktori yang sama dengan kode contoh.
"""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()

Langkah 4: Jalankan contoh

Setelah Anda mengaktifkan Analytics API, instal library klien Google API untuk Python, dan siapkan kode sumber contoh yang siap dijalankan.

Jalankan contoh menggunakan:

python HelloAnalytics.py
  1. Aplikasi ini akan memuat halaman otorisasi di browser.
  2. Jika belum login ke Akun Google, Anda akan diminta untuk login. Jika login ke beberapa Akun Google, Anda akan diminta untuk memilih satu akun yang akan digunakan untuk otorisasi.

Setelah Anda menyelesaikan langkah-langkah ini, contoh menghasilkan nama tampilan (profil) Google Analytics pertama pengguna yang diotorisasi dan jumlah sesi selama tujuh hari terakhir.

Dengan objek layanan Analytics yang diotorisasi, kini Anda dapat menjalankan contoh kode apa pun yang ada di dokumen referensi Management API. Misalnya, Anda dapat mencoba mengubah kode untuk menggunakan metode accountSummaries.list.

Pemecahan masalah

AttributeError: Objek 'Module_six_moves_urllib_parse' tidak memiliki atribut 'urlparse'

Error ini dapat terjadi di Mac OSX saat penginstalan default modul "enam" (dependensi library ini) dimuat sebelum modul yang diinstal pip. Untuk memperbaiki masalah ini, tambahkan lokasi penginstalan pip ke variabel lingkungan sistem PYTHONPATH:

  1. Tentukan lokasi penginstalan pip dengan perintah berikut:

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

  2. Tambahkan baris berikut ke file ~/.bashrc Anda, dengan mengganti <pip_install_path> dengan nilai yang ditentukan di atas:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. Muat ulang file ~/.bashrc Anda di jendela terminal yang terbuka menggunakan perintah berikut:

    source ~/.bashrc