Google Analytics

Tutorial: Hello Analytics API

Pete Frisella, Nick Mihailovski – May 2012

This tutorial walks through the steps required to access a Google Analytics account, query the Analytics APIs, handle API responses, and output the results. The Core Reporting API v3.0, Management API v3.0, and OAuth 2.0 are used for this tutorial.


  1. Introduction
  2. Select a Language
  3.  
  1. Program Overview
    1. Setup your environment
    2. Create an Analytics Service Object
      1. 1. Register an application in the Google Developers Console
      2. 2. Authorize Access to Google Analytics Data
      3. 3. Create An Analytics Service Object
    3. Query the APIs, Handle the Response, and Output the Results
      1. 1. Initialize the Analytics Service Object
      2. 2. Query the Management API
      3. 3. Query the Core Reporting API
      4. 4. Output the result
  1. Working Demos
  2. Next Steps
  3.  
  4. Code Summary: Create Service Object
  5. Code Summary: Query APIs

Introduction

Writing an application that accesses Google Analytics data is a complex process. It requires the use of various APIs and an understanding of key concepts. This tutorial walks you through each step of the process. Upon completion you will have a basic understanding of how to:

  • Authenticate and Authorize a user
  • Create an Analytics Service Object
  • Query the Core Reporting API and Management API
  • Handle API responses
  • Output results

This tutorial covers the fundamentals needed for all of the Analytics dev guides.

Select a Language

Several programming languages are covered in this tutorial. Select the language you intend to follow:

Java

Python

PHP

JavaScript

Program Overview

The example program for this tutorial will execute the following query:

Output the total number of Sessions for the first View (Profile) of an authorized Google Analytics account, for March 3, 2012.

Developing a program to do this requires the following steps:

  • Setup your environment
  • Create an Analytics Service Object
    1. Register an application in the Google Developers Console
    2. Authorize Access to Google Analytics Data
    3. Create An Analytics Service Object
  • Query the APIs, Handle the Response, and Output the Results
    1. Get an Initialized Analytics Service object.
    2. Use the Analytics Service object to query the Management API and retrieve the first View (Profile) ID for the authenticated Google Analytics Account.
    3. Use the Analytics service object and View (Profile) ID to query the Core Reporting API and retrieve the total number of sessions for March 3, 2012.
    4. Output the result

Setup your Environment

Client Library

Each tutorial requires you install and configure the appropriate client library.

Java


This tutorial uses the Google APIs Client Library for Java. Read the setup instructions to learn how to configure your Java environment.

Python


This tutorial uses the Google APIs Client Library for Python. Read Installing the library for instructions on how to setup your environment.

PHP


This tutorial uses the Google APIs Client Library for PHP. Read the Getting Started guide for instructions on how to load the client.

JavaScript


This tutorial uses the Google APIs Client Library for JavaScript. Read the Getting Started guide for instructions on how to load the client.

Create Tutorial Files

Each tutorial walks you through creating a series of files. Create these files now and add code to them as you read through the tutorial.

Java


As part of this tutorial, you will need to create a single file named HelloAnalyticsApi.java. Create this file now.

Later in this tutorial, you will need to update an additional file named client_secrets.json.

Python

As part of this tutorial, you will need to create 3 files:

  • client_secrets.json – to store your authorization credentials.
  • hello_analytics_api_v3_auth.py – to store common authorization routines.
  • hello_analytics_api_v3.py – 1 for the main program

Each of these files should be in the same directory. The next sections of the tutorial will walk you thorough how to create each file.

PHP

As part of this tutorial, you will need to create a single file named HelloAnalyticsApi.php. This file will need to reside on a server running PHP.

Go ahead and create the file now and the next sections will discuss what to put into this file.

JavaScript

As part of this tutorial, you will need to create 3 files:

  • hello_analytics_api_v3.html – to define the user interface.
  • hello_analytics_api_v3_auth.js – to handle user authorization and update UI elements based on authorization status.
  • hello_analytics_api_v3.js – to make requests to the Analytics API, handle responses, and output the results to the browser Console.

Create all 3 files now. The next section will discuss the hello_analytics_api_v3.html file.

HTML Interface

The HTML interface will allow users to interact with your application through 2 buttons. One to grant access to their Analytics account, and one to "Get Sessions" for their Analytics account.

Open the hello_analytics_api_v3.html file and copy and paste the following contents:

<!DOCTYPE>
<html>
  <head>
    <title>Hello Google Analytics API</title>
  </head>
  <body>
    <!-- The 2 Buttons for the user to interact with -->
    <button id="authorize-button" style="visibility: hidden">Authorize</button><br/>
    <button id="make-api-call-button" style="visibility: hidden">Get Sessions</button>

    <!-- These JavaScript files will be created later on in the tutorial -->
    <script src="hello_analytics_api_v3_auth.js"></script>
    <script src="hello_analytics_api_v3.js"></script>

    <!-- Load the Client Library. Use the onload parameter to specify a callback function -->
    <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
  </body>
</html>

This file loads the Google APIs Client Library for JavaScript, which is required to query the Analytics APIs. After the library has finished loading, the callback function specified with the onload parameter will be executed.

Create an Analytics Service Object

The Analytics Service Object is what you will use to make requests for Analytics data.

The steps required to create an analytics service object are:
  1. Register an application in the Google Developers Console
  2. Authorize Access to Google Analytics Data
  3. Create An Analytics Service Object

1. Register an application in the Google Developers Console

Every query made to the Analytics API must be associated with a registered project in the Google Developers Console. Without a registered project, your application will not receive full quota.

Creating a project will provide you with a Client ID and Key that will be used to identify your application when making requests to the Analytics service. To learn more about the Client IDs and Keys, read Keys, access, security, and identity

Java

Create a Developers Console Project

Application type: Installed Application
Authentication type: OAuth 2.0

If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Analytics API.
  4. In the sidebar on the left, select Credentials.

In either case, you end up on the application's credentials page.

To find your application's client ID and client secret, and set a redirect URI, expand the OAuth 2.0 Client ID section.

Write down the values for each of these fields:

  • Client ID
  • Client secret

Update and Compile Client Secrets File (client_secrets.json)

Each Java application needs to include it's Client ID and Client secret. This Java tutorial uses some helper classes (found in the Java Client Library) to simplify using these values. In this sample, you must add these values to a file named client_secrets.json. This file must then be compiled and installed. Read the Analytics Command line instructions to learn how to carry out these steps.

Once complete you are ready to continue to the next step.

Python

Create a Developers Console Project

Application type: Installed Application
Authentication type: OAuth 2.0

If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Analytics API.
  4. In the sidebar on the left, select Credentials.

In either case, you end up on the application's credentials page.

To find your application's client ID and client secret, and set a redirect URI, expand the OAuth 2.0 Client ID section.

Later in the tutorial you will need to know the:

  • Client ID
  • Client secret
  • Redirect URIs

Create a File to Store the Project Details (client_secrets.json)

The Client ID and Secret for your project will be stored in a separate file and accessed when the program runs. This information will be used when creating the Analytics Service object and will identify your application
Create a file named client_secrets.json. The contents of the file should look like:

{
  "installed": {
    "client_id": "INSERT CLIENT ID HERE",
    "client_secret": "INSERT CLIENT SECRET HERE",
    "redirect_uris": ["INSERT REDIRECT URI"],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
  }
}

Note: Insert the Client ID, Client secret, and Redirect URIs for your Google Developers Console Project.

PHP

Create a Google Developers Console Project

Application type: Web Application
Authentication type: OAuth 2.0

If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Analytics API.
  4. In the sidebar on the left, select Credentials.

In either case, you end up on the application's credentials page.

To find your application's client ID and client secret, and set a redirect URI, expand the OAuth 2.0 Client ID section.

To find your application's API key, expand the Browser Key or Server Key sections.

Later in the tutorial you will need to know the:

  • Client ID
  • Client secret
  • Redirect URIs
  • API Key

JavaScript

Create a Developers Console Project

Application type: Web Application
In the "Authorized JavaScript Origins" box, enter the protocol and domain for your site

If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Analytics API.
  4. In the sidebar on the left, select Credentials.

In either case, you end up on the application's credentials page.

To find your application's client ID and client secret, and set a redirect URI, expand the OAuth 2.0 Client ID section.

To find your application's API key, expand the Browser Key or Server Key sections.

Get your Client ID and API Key.


2. Authorize Access to Google Analytics Data

When a user starts an application built with the Google Analytics APIs, they will have to grant the application access to their Google Analytics data. This process is called authorization. The recommended method for authorizing users is OAuth 2.0. If you'd like to learn more about the OAuth 2.0 authentication protocol, read Using OAuth 2.0 to Access Google APIs.

The Auth Flow is the process of authenticating a user and requesting access to their Analytics data. If access is granted, then an Analytics Service Object is constructed, which is required to make authorized Analytics requests.

Java

HelloAnalyticsApi.java

In the previous step, you compiled the client_secrets.json file. In this step you use that compiled file to initialize an analytics service object in a method named initializeAnalytics.

The Java Client library manages a user's authorization credentials in a Credentials object. For applications run from the command line, or through an editor, the Java Client Library provides a helper class OAuth2Native that handles the command line authorization process to create the Credentials object.

Open the file you created named HelloAnalyticsApi.java and add the following method:

private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

private static final JsonFactory JSON_FACTORY = new JacksonFactory();

private static Analytics initializeAnalytics() throws Exception {
  Credential credential = OAuth2Native.authorize(
      HTTP_TRANSPORT, JSON_FACTORY, new LocalServerReceiver(),
      Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY));

  // ...
}

When a user encounters this script, the application will attempt to open the default browser and navigate the user to a URL hosted on google.com. At this point, the user will be prompted to login and grant the application access to their data. Once granted, the application will attempt to read a code from the browser window, then close the window.

If any errors occur, the application will prompt the user to add their authorization code on the command line.

Once added, the authorization flow will resume to get the proper access credentials into the Credentials object.

Python

Auth Helper (hello_analytics_api_v3_auth.py)

The Auth Helper script will handle user authentication and authorization. Specifically, this script will:

  1. Import the required classes and declare constants and objects
  2. Store credentials for authentication and authorization
  3. Construct the Analytics Service Object

Open a file named hello_analytics_api_v3_auth.py. It should be in located in the same directory as the client_secrets.json file. All of the following code snippets should be placed in the body of this file.

1. Import the required classes and declare constants and objects

A few classes need to be imported to help with OAuth 2.0, and to contruct the Analytics Service Object. Contstants will hold various configuration values needed for authentication. The scope required to access Google Analytics data is https://www.googleapis.com/auth/analytics.readonly

The following code demonstrates how to configure a client and authenticate using OAuth 2.0 for an installed application. Add the following to the body of your script:

#!/usr/bin/python

# import required classes
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run

# Declare constants and set configuration values

# The file with the OAuth 2.0 Client details for authentication and authorization.
CLIENT_SECRETS = 'client_secrets.json'

# A helpful message to display if the CLIENT_SECRETS file is missing.
MISSING_CLIENT_SECRETS_MESSAGE = '%s is missing' % CLIENT_SECRETS

# The Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message=MISSING_CLIENT_SECRETS_MESSAGE)

# A file to store the access token
TOKEN_FILE_NAME = 'analytics.dat'

Persisting Credentials

Note: This tutorial uses Storage to handle authentication persistence. This solution will only work for single-user scenarios, as there is one single storage file.

The process to persist credentials should first include a check to determine if valid credentials (i.e. an access token) already exist. If none exist then run the Auth flow and write any new credentials to the Storage object using the file name specified with the TOKEN_FILE_NAME constant.

Define the prepare_credentials() function:

def prepare_credentials():
  # Retrieve existing credendials
  storage = Storage(TOKEN_FILE_NAME)
  credentials = storage.get()

  # If existing credentials are invalid and Run Auth flow
  # the run method will store any new credentials
  if credentials is None or credentials.invalid:
    credentials = run(FLOW, storage) #run Auth Flow and store credentials

  return credentials

PHP

HelloAnalyticsApi.php

This is the main file of the application. When a user first comes to this page, they are presented with a button to authorize access to this application. When clicked, they are redirected to Google to authorize access. Once complete, they are returned to this page, at which time, the page must complete a couple of authorization steps. Finally, when all the authorization is done, the application can work with the Analytics APIs.

The PHP client library provides a number of helper classes that can be used to simplify this authorization flow. Specifically this script will need to:

  1. Load the PHP client libraries
  2. Start a session to persist credentials
  3. Create and configure a new client object
  4. Handle authorization flow from the server
  5. Retrieve and use stored credentials
  6. Either prompt the user to login -or- run the demo

In the PHP example, all the logic is done in the HelloAnalyticsApi.php file. All of the following code snippets should be placed in the body of this file.

1. Load the PHP client libraries

The first step is to load the Google API PHP Client Library. This step will vary depending on where the library is located in relationship to the HelloAnalyticsApi.php file.

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';

2. Start a session to persist credentials

Once a user authorizes access to this application, the application will store the authorized credentials in an accessToken object. To prevent the user from having to re-authorize everytime the script runs, the accessToken is stored using PHP session storage. To initialize this storage, you must call:

session_start();

3. Create and configure a new client object

To simplify the authorization process, the PHP client library provides the apiClient object. Before you can use this object you must add the: Client ID, Client Secret, Redirect URI, API Key that you retrieved through the Developers Console.

$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');

// Visit https://console.developers.google.com/ to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_developer_key');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
  • The Redirect URI should be the same URL that points to where your HelloAnalyticsApi.php file is hosted on. This value must also be configured in the Google Developers Console.
  • The Developer Key should be your API Key found in the console.
  • The $client->setUseObject(true); sets the client libraries to convert all the API responses from associative arrays into objects.

Once we have a client object, we can use it to handle the OAuth 2.0 web server authorization flow.

4. Handle authorization flow from the server

A user initiates authorization by clicking a button, added to the page in a later step in this tutorial. When they click this button, they will be sent to Google and will need to grant the application access. Once complete, Google will redirect the user back to the HelloAnalyticsApi.php page, based on the value of the Redirect URI field, and include an authorization code in the URL.

The next step is to check if the code parameter is present in the URL. If it is present, then the client object is used to continue the user through the authorization process.

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

The $client->authenticate(); method does most of the authorization work. Once complete, the client object will have a valid access token. This token is then set into the session storage. Finally the code url parameter is stripped from the URL to keep things looking neat.

5. Retrieve and use stored credentials.

As part of the previous step, the accessToken was saved in the session storage. If a user is returning to this page, and the access token exists in the session, it is retrieved and set back into the client.

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

6. Either prompt the user to login -or- run the demo.

After all the steps above, the client either does not have or has a valid access token. A check is made whether the token exists:

  • If it does not exist – The user is presented with a button to start the authorization process
  • If it does exist – The client object is used to create an authorized analytics service object.
if (!$client->getAccessToken()) {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";

} else {
  // Create analytics service object. See next step below.
}

JavaScript

Auth Helper Script (hello_analytics_api_v3_auth.js)

The Auth Helper script will handle user authentication and authorization and update UI elements based on authorization status. Specifically, this script will need to:

  1. Set the configuration values
  2. Handle the onload event for the Google APIs JavaScript Client Library
  3. Check if the user has Authenticated and Authorized
  4. Update the UI based on the user's authorization status

Open a file named hello_analytics_api_v3_auth.js. All of the following code snippets should be placed in the body of this file.

1. Set the configuration values

Use the values from your project to set the authorization config values of Client ID, API Key, and Scopes. The auth scope is https://www.googleapis.com/auth/analytics.readonly

It should look like:

var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';

2. Handle the onload event for the Google APIs JavaScript Client Library

The Google APIs JavaScript Client Library is loaded from the HTML Interface. An onload parameter is included when loading the library to specifiy a callback function to execute after the library has finished loading. We now need to define this callback function.

The function should do two things after the Client Library has loaded:

  1. Set the API Key
  2. Check if the user has been Authenticated. This is an important check prior to making queries.

Define the handleClientLoad() function to handle the onload event:

// This function is called after the Client Library has finished loading
function handleClientLoad() {
  // 1. Set the API Key
  gapi.client.setApiKey(apiKey);

  // 2. Call the function that checks if the user is Authenticated. This is defined in the next section
  window.setTimeout(checkAuth,1);
}

3. Check if the user has Authenticated and Authorized

At certain points, such as after the Client Library loads, it is important to check that the user has been authenticated and the application authorized before proceeding to make API requests. The Google Accounts service can be queried to get this status. The response it provides can be passed to a callback function to determine what to do next.

Define the checkAuth() function to carry out the Auth check:

function checkAuth() {
  // Call the Google Accounts Service to determine the current user's auth status.
  // Pass the response to the handleAuthResult callback function
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}

The checkAuth function calls the Google Accounts Service. The response from the service will be passed back to the handleAuthResult function defined in the next step

4. Update the UI based on the user's authorization status

In step 3, the Google Accounts Service was called to determine the user's auth status. Based on the service's response, the following needs to be carried out:

  • If the user has given authorization to access their data, load the Analytics client, and update the UI to show the 'Get Sessions' button and hide the 'Authoriize' button.
  • If the user has not authorized access then hide the 'Get Sessions' button and show the 'Authorize' button.
To do this, define 3 new functions:
  1. handleAuthResult() will check the response from the Google Accounts service and will determine what to do based on whether the user has or has not authorized acccess.
  2. handleAuthorized() will include all the commands to carry out if the user has authorized access.
  3. handleUnAuthorized() will include all the commands to carry out if the user has not authorized access

Add the handleAuthResult(), handleAuthorized(), and handleUnAuthorized() functions:

function handleAuthResult(authResult) {
  if (authResult) {
    // The user has authorized access
    // Load the Analytics Client. This function is defined in the next section.
    loadAnalyticsClient();
  } else {
    // User has not Authenticated and Authorized
    handleUnAuthorized();
  }
}


// Authorized user
function handleAuthorized() {
  var authorizeButton = document.getElementById('authorize-button');
  var makeApiCallButton = document.getElementById('make-api-call-button');

  // Show the 'Get Sessions' button and hide the 'Authorize' button
  makeApiCallButton.style.visibility = '';
  authorizeButton.style.visibility = 'hidden';

  // When the 'Get Sessions' button is clicked, call the makeAapiCall function
  makeApiCallButton.onclick = makeApiCall;
}


// Unauthorized user
function handleUnAuthorized() {
  var authorizeButton = document.getElementById('authorize-button');
  var makeApiCallButton = document.getElementById('make-api-call-button');

  // Show the 'Authorize Button' and hide the 'Get Sessions' button
  makeApiCallButton.style.visibility = 'hidden';
  authorizeButton.style.visibility = '';

  // When the 'Authorize' button is clicked, call the handleAuthClick function
  authorizeButton.onclick = handleAuthClick;
}

The purpose of these handler functions is to set UI elements and listeners for button clicks based on the authorization status of the user.

You'll notice that there are 2 other functions referenced in the snippet above
  • makeApiCall() is called when the 'Get Sessions' button is clicked, and will query the Analytics API. We'll deal with that in the later section.
  • handleAuthClick() is called when the 'Authorize' button is clicked and will start the auth flow that will ask the user to authenticate and authorize the application. The auth flow response will be passed to the auth handler function we defined earlier, handleAuthResult, to determine the next set of commands.

Add the handleAuthClick() function:

function handleAuthClick(event) {
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
  return false;
}

3. Create An Analytics Service Object

Java

Once we have an authorized Credential object, we can now build an Analytics service object to work with the API.

Add the following line of code to the initializeAnalytics method defined above.

Analytics analytics = Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY)
  .setApplicationName("Hello-Analytics-API-Sample")
  .setHttpRequestInitializer(credential)
  .build();

The HTTP_TRANSPORT and JSON_FACTORY parameters are the same objects created in the previous step. The setHttpRequestInitializer method accepts the validated Credential object.

Once created, we now have a valid Google Analytics Service object that can be used with any of the Google Analytics APIs.

Python

Now that we have gained authorization to access the user's Google Analytics data, we need to use that authorization and apply it to an http object. The http object will be used to create an Analytics service object. The steps to accomplish this are:

  1. Create an http object
  2. Authorize the http object using the authorization credentials we obtained earlier
  3. Build the Analytics Service Object with the authorized http object

Define the initialize_service() function to carry out these steps:

def initialize_service():
  # 1. Create an http object
  http = httplib2.Http()

  # 2. Authorize the http object
  # In this tutorial we first try to retrieve stored credentials. If
  # none are found then run the Auth Flow. This is handled by the
  # prepare_credentials() function defined earlier in the tutorial
  credentials = prepare_credentials()
  http = credentials.authorize(http)  # authorize the http object

  # 3. Build the Analytics Service Object with the authorized http object
  return build('analytics', 'v3', http=http)

PHP

In the previous step we created an authorized client object. In this step we use it to create an authorized analytics service object.

The following code should be placed inside the else code block defined in the previous section.

$analytics = new apiAnalyticsService($client);
runMainDemo($analytics);

Once the new apiAnalyticsService object is created, it is passed to the runMainDemo function to use it to make API requests.

JavaScript

Now that we have gained authorization to access the user's Google Analytics data we need to load the Analytics client.

It is important to make sure the Analytics client has loaded before updating UI elements. This will ensure that the user does not click a button before the client is ready to execute queries. To do this we can specify a callback function when loading the Analytics client, in this case handleAuthorized(). This function will run once the Analytics client has loaded.

Define the loadAnalyticsClient() function:

function loadAnalyticsClient() {
  // Load the Analytics client and set handleAuthorized as the callback function
  gapi.client.load('analytics', 'v3', handleAuthorized);
}

This will load the Analytics Client and then call the handleAuthorized() function that will update the UI elements and add an onclick event to the "Get Sessions" button.

Next Steps

At this point in the tutorial you have learned how to:
  1. Register an application in the Google Developers Console
  2. Authorize Access to Google Analytics Data
  3. Create An Analytics Service Object

You are now able to use the Analytics Service Object to query the Google Analytics APIs.



Query the Management API, Core Reporting API, and Output the Results

Now we can use the Analytics Service Object to query the Management API to retrieve the first View (Profile) ID, and then query the Core Reporting API with the view (profile) ID to retrieve the total number of sessions for March 3, 2012. The responses for each query will need to be handled, and the results outputted to the user. The following steps are required to accomplish this process:

  1. Get an initialized analytics service object
  2. Get the user's first view (profile) ID
  3. Query the Core Reporting API
  4. Output the result

1. Get an initialized analytics service object

You use the analytics service object obtained in the previous step to query the Management API, and Core Reporting API.

In this step, the example sets up the main program to go through each of these steps. It also retrieves an initialized analytics service object.

Java

HelloAnalyticsApi.java

This sample continues from the first half of our tutorial. In each step, continue adding code to the HelloAnalyticsApi.java file.

The initializeAnalytics method can be used to return an Analytics Service object that can be used to work with the Google Analytics API.

public static void main(String[] args) {
  try {
    // Step 1. Get an analytics service object.
    Analytics analytics = initializeAnalytics();

    // Step 2. Get the user's first view (profile) ID.
    String profileId = getFirstProfileId(analytics);

    if (profileId != null) {

      // Step 3. Query the Core Reporting API.
      GaData gaData = getResults(analytics, profileId);

      // Step 4. Output the results.
      printResults(gaData);
    }
  } catch (GoogleJsonResponseException e) {
    System.err.println("There was a service error: " + e.getDetails().getCode() +
        " : " + e.getDetails().getMessage());
  }
   catch (Throwable t) {
    t.printStackTrace();
  }
}

If the Analytics Service object encounters any problems, a GoogleJsonResponseException is thrown. You can use this object to get the API and a descriptive status message of what went wrong.

If no exceptions are thrown, you are ready to start working with the Analytics API.

Python

The Program (hello_analytics_api_v3.py)

The Auth Helper class created in the first half of this tutorial can be used to get an initialized analytics service object by calling the initialize_service function.

Create a file named hello_analytics_api_v3.py in the same directory as client_secrets.json, and hello_analytics_api_v3_auth.py.

The following needs to be added to the hello_analytics_api_v3.py file:
  1. Import the required classes including the Auth Helper created earlier, hello_analytics_api_v3_auth.py.
  2. Add a main function and get an initialize Analytics Service Object by calling the initialize_service() function from the Auth Helper class (hello_analytics_api_v3_auth).

It should look like:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

# import the Auth Helper class
import hello_analytics_api_v3_auth

from apiclient.errors import HttpError
from oauth2client.client import AccessTokenRefreshError

def main(argv):
  # Step 1. Get an analytics service object.
  service = hello_analytics_api_v3_auth.initialize_service()

  try:
    # Step 2. Get the user's first profile ID.
    profile_id = get_first_profile_id(service)

    if profile_id:
      # Step 3. Query the Core Reporting API.
      results = get_results(service, profile_id)

      # Step 4. Output the results.
      print_results(results)

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)

  except HttpError, error:
    # Handle API errors.
    print ('Arg, there was an API error : %s : %s' %
           (error.resp.status, error._get_reason()))

  except AccessTokenRefreshError:
    # Handle Auth errors.
    print ('The credentials have been revoked or expired, please re-run '
           'the application to re-authorize')

In this example, step 1 returns the analytics service object. Then this service object is passed to 3 methods that will work with the API. Some try and catch statements have been added to catch any APIs errors.

PHP

HelloAnalyticsApi.php

This sample continues from the first half of our tutorial. In each step, continue adding code to the HelloAnalyticsApi.php file.

In the previous step, you created an authorized analytics service object and passed the object to a method named runMainDemo. This method will be used to work with the Analytics APIs.

function runMainDemo(&$analytics) {
  try {

    // Step 2. Get the user's first view (profile) ID.
    $profileId = getFirstProfileId($analytics);

    if (isset($profileId)) {

      // Step 3. Query the Core Reporting API.
      $results = getResults($analytics, $profileId);

      // Step 4. Output the results.
      printResults($results);
    }

  } catch (apiServiceException $e) {
    // Error from the API.
    print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();

  } catch (Exception $e) {
    print 'There wan a general error : ' . $e->getMessage();
  }
}

In this example, step 1: get an authorized analytics service object, is done in the previous section of the tutorial and the analytics object is passed as a parameter into the runMainDemo method.

The authorized analytics service object is then passed to functions for each step of the application. If any Exceptions are thrown, they are caught and their message is displayed to the user.

JavaScript

At this point in the tutorial we have created the HTML Interface and the Auth Helper script. The tasks accomplished with these 2 files were to load the Analytics client and authorize the user.

Now we can use the Analytics Client to query the Management API to get the first view (profile) ID. All of the functions for making requests and handling responses will be placed in a separate JavaScript file described below:

API Requests & Response Handler (hello_analytics_api_v3.js)

The API Requests & Response handler script will use the Analytics client to makes requests to the Analytics API, handle responses, and output results to the browser Console.

In the auth helper section, makeApiCall() was set as the function to invoke on the click of the "Get Data" button. This function needs to be defined and it should start the process of making and handling queries to the Analytics service.

Open a new file named hello_analytics_api_v3.js and add the following:

function makeApiCall() {
  queryAccounts();
}

In this example, makeApiCall() simply calls queryAccounts(), a function written to query account configuration data. This approach provides greater flexibility in case you want to carry out additional commands when the user clicks the "Get Data" button. It also makes the script easier to follow.

Once complete, you've just setup your main program and have retrieved an authorized service object. You've also defined a series of methods to use the service object to retrieve analytics data.

In the following steps, you'll implement each of these methods to get a working program.


2. Get the user's first view (profile) ID

Use the Analytics Service object to query the Management API and retrieve the first View (Profile) ID for the Google Analytics Account.

Java

The following example traverses down through the Management API hierarchy to retrieve the first view (profile) ID for the authorized user.

private static String getFirstProfileId(Analytics analytics) throws IOException {
  String profileId = null;

  // Query accounts collection.
  Accounts accounts = analytics.management().accounts().list().execute();

  if (accounts.getItems().isEmpty()) {
    System.err.println("No accounts found");
  } else {
    String firstAccountId = accounts.getItems().get(0).getId();

    // Query webproperties collection.
    Webproperties webproperties = analytics.management().webproperties()
        .list(firstAccountId).execute();

    if (webproperties.getItems().isEmpty()) {
      System.err.println("No Webproperties found");
    } else {
      String firstWebpropertyId = webproperties.getItems().get(0).getId();

      // Query profiles collection.
      Profiles profiles = analytics.management().profiles()
          .list(firstAccountId, firstWebpropertyId).execute();

      if (profiles.getItems().isEmpty()) {
        System.err.println("No views (profiles) found");
      } else {
        profileId = profiles.getItems().get(0).getId();
      }
    }
  }
  return profileId;
}

Once complete, the view (profile) ID for the user's first view (profile) is returned.

Python

Query the Management API to get the first view (profile) id of a Google Analytics Account. The function will need to use an authorized Analytics service object to traverse the Management API and return the first view (profile) id.

Define the get_first_profile_id() function. Add this to your Program (hello_analytics_api_v3.py):

def get_first_profile_id(service):
  # Get a list of all Google Analytics accounts for this user
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account
    firstAccountId = accounts.get('items')[0].get('id')

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

    if webproperties.get('items'):
      # Get the first Web Property ID
      firstWebpropertyId = webproperties.get('items')[0].get('id')

      # Get a list of all Views (Profiles) for the first Web Property of the first Account
      profiles = service.management().profiles().list(
          accountId=firstAccountId,
          webPropertyId=firstWebpropertyId).execute()

      if profiles.get('items'):
        # return the first View (Profile) ID
        return profiles.get('items')[0].get('id')

  return None

The function queries the Management API to get the first account, then queries for the first web property of the first account, and finally queries for the first view (profile) id of the first web property. It then returns the first view (profile) id

PHP

The following example traverses down through the Management API hierarchy to retrieve the first view (profile) ID for the authorized user.

function getFirstprofileId(&$analytics) {
  $accounts = $analytics->management_accounts->listManagementAccounts();

  if (count($accounts->getItems()) > 0) {
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    $webproperties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

    if (count($webproperties->getItems()) > 0) {
      $items = $webproperties->getItems();
      $firstWebpropertyId = $items[0]->getId();

      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstWebpropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();
        return $items[0]->getId();

      } else {
        throw new Exception('No views (profiles) found for this user.');
      }
    } else {
      throw new Exception('No webproperties found for this user.');
    }
  } else {
    throw new Exception('No accounts found for this user.');
  }
}

The function queries the Management API to get the first account, then queries for the first web property of the first account, and finally queries for the first view (profile) id of the first web property. It then returns the first view (profile) id

JavaScript


Using the Google APIs Javascript Client library to query the Google Analytics APIs involves two basic steps:
  • Make the Request and
  • Handle the Response

In practice, it requires multiple requests and callback functions.

For example, the steps to get the first View (Profile) ID are:
  1. Query the Management API for a list of the user's Accounts.
  2. Use the response from Step 1. to identify the first Google Analytics Account. Query the Management API for a list of Web Properties from the first Account.
  3. Use the response from Step 2. to identify the first Web Property. Query the Management API for a list of View (Profile) IDs from the first Web Property.
  4. Use the response from Step 3. to identify the first View (Profile) ID.
  5. Use the first View (Profile) ID identified in Step 4., construct a query and query the Core Reporting API.

Add the following to the body of API Requests & Response Handler (hello_analytics_api_v3.js):

function queryAccounts() {
  console.log('Querying Accounts.');

  // Get a list of all Google Analytics accounts for this user
  gapi.client.analytics.management.accounts.list().execute(handleAccounts);
}

function handleAccounts(results) {
  if (!results.code) {
    if (results && results.items && results.items.length) {

      // Get the first Google Analytics account
      var firstAccountId = results.items[0].id;

      // Query for Web Properties
      queryWebproperties(firstAccountId);

    } else {
      console.log('No accounts found for this user.')
    }
  } else {
    console.log('There was an error querying accounts: ' + results.message);
  }
}

function queryWebproperties(accountId) {
  console.log('Querying Webproperties.');

  // Get a list of all the Web Properties for the account
  gapi.client.analytics.management.webproperties.list({'accountId': accountId}).execute(handleWebproperties);
}

function handleWebproperties(results) {
  if (!results.code) {
    if (results && results.items && results.items.length) {

      // Get the first Google Analytics account
      var firstAccountId = results.items[0].accountId;

      // Get the first Web Property ID
      var firstWebpropertyId = results.items[0].id;

      // Query for Views (Profiles)
      queryProfiles(firstAccountId, firstWebpropertyId);

    } else {
      console.log('No webproperties found for this user.');
    }
  } else {
    console.log('There was an error querying webproperties: ' + results.message);
  }
}

function queryProfiles(accountId, webpropertyId) {
  console.log('Querying Views (Profiles).');

  // Get a list of all Views (Profiles) for the first Web Property of the first Account
  gapi.client.analytics.management.profiles.list({
      'accountId': accountId,
      'webPropertyId': webpropertyId
  }).execute(handleProfiles);
}

function handleProfiles(results) {
  if (!results.code) {
    if (results && results.items && results.items.length) {

      // Get the first View (Profile) ID
      var firstProfileId = results.items[0].id;

      // Step 3. Query the Core Reporting API
      queryCoreReportingApi(firstProfileId);

    } else {
      console.log('No views (profiles) found for this user.');
    }
  } else {
    console.log('There was an error querying views (profiles): ' + results.message);
  }
}

Now that the first view (profile) ID has been retrieved, the next step is to query the Core Reporting API with the view (profile) id. The queryCoreReportingApi() function defined in the snippet above is discussed in the next section.


3. Query the Core Reporting API

Now that we have a user's view (profile) ID, we can use the ID to form a Core Reporting API query. In this example we build a query to return the total number of sessions for March 3, 2012

Java

private static GaData getResults(Analytics analytics, String profileId) throws IOException {
  return analytics.data().ga()
      .get("ga:" + profileId,        // Table Id. ga: + profile id.
          "2012-03-03",              // Start date.
          "2012-03-03",              // End date.
          "ga:sessions")               // Metrics.
      .execute();
}

In this example, getResults accepts the analytics service object as well as a view (profile) ID retrieved in the previous step. The query is then built using the get method and issued to the API using the execute method. If successful, the API results are returned. If an error occurs, an Exception is thrown.

  • If an error occurs – an IOException is thrown.
  • If successful – the final Core Reporting API results are returned.

Python

def get_results(service, profile_id):
  # Use the Analytics Service Object to query the Core Reporting API
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='2012-03-03',
      end_date='2012-03-03',
      metrics='ga:sessions').execute()

In this example, the get_results method accepts the analytics service object as well as the view (profile) ID retrieved in the previous step. The query is then built using the get method and issued to the API using the execute method. If successful, the API results are returned. If an error occurs, an Exception is thrown.

PHP

function getResults(&$analytics, $profileId) {
   return $analytics->data_ga->get(
       'ga:' . $profileId,
       '2012-03-03',
       '2012-03-03',
       'ga:sessions');
}

In this example, the getResults method accepts the analytics service object as well as the view (profile) ID retrieved in the previous step. The query is both built and executed using the get method. If successful, the API results are returned. If an error occurs, an Exception is thrown.

JavaScript

function queryCoreReportingApi(profileId) {
  console.log('Querying Core Reporting API.');

  // Use the Analytics Service Object to query the Core Reporting API
  gapi.client.analytics.data.ga.get({
    'ids': 'ga:' + profileId,
    'start-date': '2012-03-03',
    'end-date': '2012-03-03',
    'metrics': 'ga:sessions'
  }).execute(handleCoreReportingResults);
}

function handleCoreReportingResults(results) {
  if (results.error) {
    console.log('There was an error querying core reporting API: ' + results.message);
  } else {
    printResults(results);
  }
}

In this example, the queryCoreReportingApi function accepts the view (profile) ID retrieved in the previous step. The query is then built using the gapi.client.analytics.data.ga.get method and issued to the API using the execute method.

The execute method accepts a callback function as a parameter. When execute is called, an asynchronous request is made to Google Analytics. Once the API responds, handleCoreReportingResuls is executed and passed the results from the API.

Finally, a check to ensure there was no error is made, then the results are passed to printResults to be printed.


4. Output the result

The last step in the program is to output the results returned from the Core Reporting API.

Java

The final step is to print out all the results.

private static void printResults(GaData results) {
  if (results != null && !results.getRows().isEmpty()) {
    System.out.println("View (Profile) Name: " + results.getProfileInfo().getProfileName());
    System.out.println("Total Sessions: " + results.getRows()[0][0]);
  } else {
    System.out.println("No results found");
  }
}

Python

The final step is to print out all the results:

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

  else:
    print 'No results found'

PHP

The final step of the code is to print the total number of sessions. This is done in the printResults function.

function printResults(&$results) {
  if (count($results->getRows()) > 0) {
    $profileName = $results->getProfileInfo()->getProfileName();
    $rows = $results->getRows();
    $sessions = $rows[0][0];

    print "<p>First view (profile) found: $profileName</p>";
    print "<p>Total sessions: $sessions</p>";

  } else {
    print '<p>No results found.</p>';
  }
}

JavaScript

The final step of the code is to print the total number of sessions. This is done in the printResults function.

function printResults(results) {
  if (results.rows && results.rows.length) {
    console.log('View (Profile) Name: ', results.profileInfo.profileName);
    console.log('Total Sessions: ', results.rows[0][0]);
  } else {
    console.log('No results found');
  }
}

In this example console.log is used to print the results to the console.


Working Demos

Java

Google API Java Client Library Hello Analytics API Sample

Python

Google API Python Client Library Hello Analytics API Sample

JavaScript

Google API JavaScript Client Library Hello Analytics API Sample

Next Steps

Now that you've learned how to build a working program that uses the Google Analytics APIs, read our developer guides to learn more about how to work with the APIs.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.