My favorites | English | Sign in

Faster JavaScript with Closure Tools New!

Google Analytics (Labs)

Data Export API - JavaScript

This document is a tutorial that walks you through creating a fully-functional sample application using the JavaScript client library.

    1. Why Read this Document?
    2. Set Up Your HTML File
      1. Reference the JavaScript
      2. Put in User Controls
      3. Set up the Display Container
      4. Reference the Hidden Image
    3. Set Up Your JavaScript File
      1. Load the Google Analytics Library
      2. Initialize Your Application
      3. Setup Data Controls
    1. Retrieve Account Data
      1. Set Up the getAccountFeed Method
      2. Handle the Request 
    2. Retrieve Report Data
      1. Set Up the getDataFeed Method
      2. Handle the Request 
    3. Handle Errors
    4. Further Resources
      1. Query Explorer
      2. Feed Reference
      3. Interactive Examples

Why Read this Document?

If you want to retrieve Google Analytics data using the Data Export API, and are new to using the Google Data JavaScript client library, this is a good place to start. If you have more experience, you might want to start with the JavaScript examples in the Client Libraries & Sample Code section of this site.

This tutorial uses two files—HTML and JavaScript. You can download the gettingStarted.html file and the gettingStarted.js file from our resources section to follow along with this document, which covers each file in detail. When both files are placed on a web server in the same directory, the HTML will do the following:

  • Authorize the sample JavaScript application to access a user's Google Analytics Data
  • Display the first 50 account/profiles and table IDs the user has access to
  • Allow a user to insert a profile/table ID into a form and retrieve the top 10 pageviews for that profile

This document assumes that you understand HTML, know some JavaScript, and have a webserver to host your example files.

Once you have completed the tutorial (or if you want to bypass the tutorial) use the Further Resources section to learn how to customize your application further.

Set Up Your HTML File

This section covers in detail all the elements that go into creating your HTML file. You can view the file in its entirety by expanding the description, or you can download the file to your own computer to view along with this part of the tutorial.

View the HTML File Show rest of description Hide rest of description

Reference the JavaScript

The head of your HTML page contains two JavaScript references. The first calls the Ajax API Loader used to fetch the Google Data API. For details on loading the Google Data JavaScript library, see Using the JavaScript Client Library.

The second script is the JavaScript file that contains your application. It contains a number of useful utilities, plus the two methods that retrieve Google Analytics account and profile data.

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="gettingStarted.js"></script>

Back to Top

Put in User Controls

Your HTML page will need to allow users to login and log out, as well as to request account or report data. The first button in this code snippet allows your users to log in or to log out. Initially the button displays the text Loading... but once the Google Data libraries are loaded and the login status of the user is verified, it will display either Login or Logout, depending upon the status of the user.

<button id="authButton">Loading...</button>
<div id="dataControls" style="display:none">
<p>
For this user, retrieve the first 50 accounts with profile ID and table ID
<button id="getAccount">Get Account Data</button>
</p>
<p>
For this profile, show top 10 pageviews in descending order:
<input type="text" id="tableId"/> (insert Table ID)
<button id="getData">Get Report Data</button>
</p>
</div>

The remaining two buttons provide a way for your users to request Account feed data and Report feed data. The input field provides a place for the user to indicate which profile to retrieve report data from. To retrieve data from a specific profile, you need the table ID for that profile. The table ID is the unique identifier for each profile in Analytics and consists of the namespace ga: plus the profile ID. Each data feed request made to the Data Export API must contain the table ID of the profile. See the Data Feed Reference for the structure of a request to learn more.

All of these elements are contained in the dataControls container, which is toggled for display depending upon the login status of the user.

Back to Top

Setup the Display Container

Once your users click on one of the buttons on the page, the resulting data is written to the display container, which exists in the HTML as a named element to receive the output from the JavaScript application.

<div id="outputDiv"></div>

The display container shows only one set of results at a time: either the results when the user clicks on the Get Account Data button or the results from the Get Report Data button. It will not show both result sets at once. Of course, you could customize the application to display both the report data and the account data at the same time.

Reference the Hidden Image

Finally, your page must contain a hidden image in order for the JavaScript client library to load correctly. This image needs to be hosted on your own domain, but it doesn't have to actually exist or be visible.

<img src="dummy.gif" style="display:none" alt="required for Google Data"/>

Back to Top

Set Up Your JavaScript File

This section covers how to set up utilities necessary for your JavaScript file.

Load the Google Analytics Library

The first line of code loads the Google Analytics API JavaScript package from the latest version of the Google Data JavaScript library. The second parameter to google.load() is the requested version number of the JavaScript client library. In this example, 1.x retrieves the latest revision of major version 1. Finally, the third parameter indicates the Google Data package to load. If the package is not specified, all Google Data API packages will be loaded at once. For details on loading a specific client library version, see "Loading the Library" in the Google Data JavaScript Client Library guide.

// Load the Google data JavaScript client library  
google.load('gdata', '1.x', {packages: ['analytics']});

// Set the callback function when the library is ready  
google.setOnLoadCallback(init);    

The JavaScript library is loaded asynchronously, and for this reason, the AJAX loader provides a setOnLoadCallback() method to let you know when the load has finished. You can use this method to execute the part of your application that relies on the libraries. In the case above, the init function executes once the JavaScript libraries have loaded to the browser.

Back to Top

Initalize Your Application

The init() function sets up the foundation of your application and is the callback handler to the Google Data Library loader. At this point, all of the Data Export API libraries are loaded and its methods ready to use.

First, it creates a new AnalyticsService object from the Google Data service package and provides it with a name. The AnalyticsService object provides access to all the methods used to retrieve feed data from Analytics. In order to access any Google Data feed, your application must create a new object of that class with a name that you provide as a string. The string is required and can be any alphanumeric text. A recommended practice is to use your application and or company name. See the AnalyticsService reference doc for details.

Next, the init() function creates a global scope variable for Google Analytics. The scope ties an authorizaton token to a particular service, in this case, Analytics. Once the application receives the authorization token for a particular service, it can re-use that same token for sub-directories of the feed, like /accounts and /data. In this way, authorization happens once for the entire service. You could even use this part of the code to initialize other Google Data services, and re-use the token across multiple feed requests, should your application use other Google Data services in addition to Analytics.

function init() {
    myService = new google.gdata.analytics.AnalyticsService('gaExportAPI_acctSample_v1.0');
    scope = 'https://www.google.com/analytics/feeds';
    var button = document.getElementById('authButton');

    // Add a click handler to the authorize button.
    button.onclick = function() {
      // Test if the user is not authorized
      if (!google.accounts.user.checkLogin(scope)) {
        // Authorize the user.
        google.accounts.user.login(scope);
      } else {
        // Log the user out.
        google.accounts.user.logout();
        getStatus();
      }
    }
    getStatus();
}    

Finally, the remaining part of the init() function provides an onclick handler for the user login button. The authorization button toggles between log-in and log-out depending upon the value returned by the getStatus() method.

Back to Top

Set Up Data Controls

The getStatus() function of the sample application sets up three user controls, determines whether the user is logged in or logged out, and sets the display of the dataControls <div> depending upon the authorization status of the user.

If the user is logged out:

  • Sets the text of loginButton to Access Google Analytics so the login button has the correct message.
  • Hides the display of the <div> element dataControls so that the user does not see the Get Account Data and Get Report Data buttons and the Table ID input.

If the user is logged in:

  • Sets the text of loginbutton to Logout so that the user can revoke their authorization token from the application.
  • Shows the <div> element dataControls so that the user can click the Get Account Data and Get Report Data buttons and insert a profile ID into the Table ID input.
function getStatus() {
    var getAccountButton = document.getElementById('getAccount');
    getAccountButton.onclick = getAccountFeed;

    var getDataButton = document.getElementById('getData');
    getDataButton.onclick = getDataFeed;

    var dataControls = document.getElementById('dataControls');
    var loginButton = document.getElementById('authButton');
    if (!google.accounts.user.checkLogin(scope)) {
      dataControls.style.display = 'none';   // hide control div
      loginButton.innerHTML = 'Access Google Analytics';
    } else {
      dataControls.style.display = 'block';  // show control div
      loginButton.innerHTML = 'Logout';
    }
}  

Back to Top

Retrieve Account Data

The sample JavaScript application has two main functions, and the getAccountFeed() function is the first. Before your application can display Analytics report data, it must first know which profile to draw the data from. In order to do this, you use the account feed to retrieve a list of profiles that the user has access to, sorted by account.

Set Up the getAccountFeed Method

The getAccountFeed() method is a simple feed request to the AnalyticsService object defined earlier in the application. In this code snippet, the function calls the getAccountFeed() method with three parameters:

  • a feed URI
  • a continuation method to execute after the feed data is returned
  • an error handling method to execute if the feed request returns an error instead of data
function getAccountFeed() {
  var myFeedUri =
      'https://www.google.com/analytics/feeds/accounts/default?max-results=50';
  myService.getAccountFeed(myFeedUri, handleAccountFeed, handleError);
}

This feed request returns the first 50 profiles available to the user accessing the feed. For example, if the user of your application has access to 3 different Analytics accounts, each with 25 profiles (that they also have access to), this request would return a list of profiles for the first two accounts. You can customize this portion of the application to return different sets of results. See the Account Feed reference for details.

Back to Top

Handle the Request

Once the application retrieves the account feed data, it calls the handleAccountFeed() function, which loops through each entry in the account feed results and displays them as a row in a nicely formatted table on the HTML page.

Keep in mind that this example retrieves only the entries for the account feed. For a list of all the elements that can be returned from an account feed, see "Account Feed Response" in the Account Feed Reference. In addition, for more illustrations about how to display data from a feed, see the Foundational Samples in the Client Libraries & Sample Code section of this site.

function handleAccountFeed(result) {
  // An array of analytics feed entries.
  var entries = result.feed.getEntries();

  // Create an HTML Table using an array of elements.
  var outputTable = ['<table><tr>',
                     '<th>Account Name</th>',
                     '<th>Profile Name</th>',
                     '<th>Profile ID</th>',
                     '<th>Table Id</th></tr>'];

  // Iterate through the feed entries and add the data as table rows.
  for (var i = 0, entry; entry = entries[i]; ++i) {

    // Add a row in the HTML Table array for each value.
    var row = [
      entry.getPropertyValue('ga:AccountName'),
      entry.getTitle().getText(),
      entry.getPropertyValue('ga:ProfileId'),
      entry.getTableId().getValue()
    ].join('</td><td>');
    outputTable.push('<tr><td>', row, '</td></tr>');
  }
  outputTable.push('</table>');

  // Insert the table into the UI.
  document.getElementById('outputDiv').innerHTML =
      outputTable.join('');
}

Back to Top

Retrieve Report Data

The second main function of the sample application is the getDataFeed() function. This part of the application is designed to retrieve and display data from a profile returned from the getAccountFeed() function. In this part of your application, the user must enter the Table ID of the selected profile in the input box in order to retrieve the profile data.

Set Up the getDataFeed Method

The getDataFeed() method is a simple feed request to the AnalyticsService object defined earlier in the application. In this code snippet, the function calls the getDataFeed() method with three parameters:

  • a feed URI
  • a continuation method to execute after the feed data is returned
  • an error handling method to execute if the feed request returns an error instead of data
function getDataFeed() {
var myFeedUri = 'https://www.google.com/analytics/feeds/data' +
    '?start-date=2009-04-01' +
    '&end-date=2009-04-30' +
    '&dimensions=ga:pageTitle,ga:pagePath' +
    '&metrics=ga:pageviews' +
    '&sort=-ga:pageviews' +
    '&max-results=10' +
    '&ids=' + document.getElementById('tableId').value;
  
  myService.getDataFeed(myFeedUri, handleDataFeed, handleError);
}

The feed returns the first 10 pages for the indicated profile, sorted in descending order. It retrieves the page title and the path for the page and the number of pageviews for each in order to achieve this. The feed URI defines the data returned by your application, and a core part of requesting data from Analytics. You can customize this request in a variety of ways, all of which are described in the Data Feed Reference.

Back to Top

Handle the Request

Once the application retrieves the report data, it calls the handleDataFeed() function, which extracts the entries from the data feed results via an object returned from the feed handler. The results from the data feed contain a number of elements that you can display. This example retrieves only the entries from the data feed, looping through each and displaying them as a row in a table that is output to the display container of the HTML page.

Keep in mind that this example retrieves only the entries for the data feed. For a list of all the elements that can be returned from a data feed, see "Data Feed Response" in the Data Feed Reference. In addition, for more illustrations about how to display data from a feed, see the Foundational Samples in the Client Libraries & Sample Code section of this site.

/**
 * Handle the data returned by the Export API by constructing the 
 * inner parts of an HTML table and inserting into the HTML File.
 * @param {object} result Parameter passed back from the feed handler.
 */
function handleDataFeed(result) {
 
 // An array of Analytics feed entries.
 var entries = result.feed.getEntries();
 
 // Create an HTML Table using an array of elements.
 var outputTable = ['<table><tr>',
                    '<th>Page Title</th>',
                    '<th>Page Path</th>',
                    '<th>Pageviews</th></tr>'];

  // Iterate through the feed entries and add the data as table rows.
  for (var i = 0, entry; entry = entries[i]; ++i) {

     // Add a row in the HTML Table array.
     var row = [
       entry.getValueOf('ga:pageTitle'),
       entry.getValueOf('ga:pagePath'),
       entry.getValueOf('ga:pageviews')
     ].join('</td><td>');
     outputTable.push('<tr><td>', row, '</td></tr>');
   }
   outputTable.push('</table>');

  // Insert the table into the UI.
  document.getElementById('outputDiv').innerHTML =
      outputTable.join('');
}

Back to Top

Handle Errors

The final part of your application handles any error from the account or data feed request. If the either the account feed request or the data feed request fails, the function passed thorugh the errorHandler parameter is executed, and the JavaScript client library passes an error object to this function. The following simple error handler function alerts the error message to the window.

function handleError(e) {
    var error = 'There was an error!\n';
    if (e.cause) {
      error += e.cause.status;
    } else {
      error.message;
    }
    alert(error);
}  

Back to Top

Further Resources

Now that you've completed this tutorial, you should have a working application if you host both files on a web server. You can work on customizing your application to suit your needs by using the following resources.

Data Feed Query Explorer

Use the Data Feed Query Explorer to quickly and easily craft a data feed URI to retrieve, filter, and sort the data from a report. After you refine the query URI you want, copy the resultant URI from the query explorer and use it in your application. In the example above, you would insert the feed URI as the myFeedURI string in the getDataFeed() function.

Feed Reference

For details on the structure of both account and data feed request and response elements, see the Account Feed and Data Feed reference.

Interactive Examples

For more ways to explore how you might use Analytics to retrieve data for your application, the Interactive Examples page provides a code playground where you can customize, view, and test various data and account feed requests.

Back to Top