This document covers the basic steps of using Java to access your Google Analytics Data with the Google Analytics Core Reporting API. It assumes you have basic knowledge of the Java programming language.
Before You Start
You will get the most out of this document if you are familiar with the following:
- Data Retrieval Basics for Analytics.
- The data feed basic format. Use the Data Feed Query Explorer for a quick way to create a data feed query. See the Data Feed reference (query and response).
- Java Programming.
In Google Analytics, each account can have any number of reporting views (profiles).
In order to access Analytics data through the API, you'll need to use both
an account feed and a data feed. The account
feed exposes a Table ID, which uniquely identifies each view (profile) a user can
access in an account. Your application supplies the table ID to request data
from a particular view (profile), which is then returned in the data feed.
The Java client library simplifies retrieving Analytics data
by handling authorization tokens and by returning Analytics data from the
Export API in Java objects.
Once you've authorized access to the API, you follow these steps to get data
from either feed:
- Create a query to define the data you want to extract through the Google
Analytics API.
- Request data by passing caling the
getFeed
method on an authorizedAnalyticsService
object. - Use the helper classes from the client library to handle the data returned from the API request.
Set Up Your Environment
Google provides a Java client library to simplify use of any Google Data API with the Java language. You can get this library for the Analytics Core Reporting API in one of two ways:
- Using the Eclipse IDE
- Use the Google Data plugin for Eclipse. (You can also view the YouTube video instructions for how to install this plugin)
- Get the client libraries by reading the Using Eclipse with Google Data APIs tutorial.
- Using other development environments
Follow the Getting Started with the Google Data Java Client Library.
Once you have your IDE set up correctly with the Google Data client libraries,
reference the following JAR
files in your CLASSPATH
:
gdata-analytics-2.1.jar gdata-analytics-meta-2.1.jar gdata-core-1.0.jar google-collect-1.0-rc1.jar jsr305.jar
Analytics Account Authorization
Before users can view reports on the Google Analytics web site, they must
first log in with valid a Google Account. In the same way, your Java application
must provide user access to Analytics, and it will use the setUserCredentials()
method
on the AnalyticsService
object,
which handles all interaction between the Google Data API Java Library
and the Analytics Core Reporting API.
With the AnalyticsService
object, you can authorize your users
with three different methods:
- ClientLogin
- Auth Sub
- OAuth
The Google Analytics Authorization document describes which authorization method you should use depending on the type of application you are building.
This example uses the simplest ClientLogin
method. Here, two constants
hold the user name and password.
// Credentials for ClientLogin Authorization. private static final String CLIENT_USERNAME = "INSERT_LOGIN_EMAIL_HERE"; private static final String CLIENT_PASS = "INSERT_PASSWORD_HERE";
The service object is created next. The parameter to the service object is
a string that represents the name of your application. After that, authorization
to Analytics is handled with the setUserCredentials
method.
// Service Object to work with the Google Analytics Core Reporting API. AnalyticsService analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0"); // ClientLogin Authorization. analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
For more information on authorization, see the Google Data API guides for the following, each of which contain examples for Java:
Retrieving Report Data
Once the account feed retrieves the valid table IDs for each view (profile), your application uses them to construct a data feed query. The data feed gets view (profile) data through the API. Because the table ID is a unique identifier for each view (profile), it is a required parameter in the query in order to indicate which view (profile) to retrieve data from.
In our example, the application supplies the table ID of
the view (profile) to access in the TABLE_ID
constant.
... private static final String TABLE_ID = "INSERT_TABLEID_HERE"; ...
In the main()
method, the code ensures the table ID has been
set before requesting data from the data feed.
... if (!TABLE_ID.isEmpty()) { getDataFeed(analyticsService); } ...
As with the account feed, the first part of requesting data involves constructing
a feed request URL. To do this, you can use the DataQuery
class
of the Java client library, which simplifies constructing data queries to the
API. In this example, a new DataQuery
object requests
the top 10 URLs, titles, and pageviews for the month of April 2009.
// Create a query using the DataQuery Object. DataQuery query = new DataQuery(new URL( "https://www.google.com/analytics/feeds/data")); query.setStartDate("2009-04-01"); query.setEndDate("2009-04-30"); query.setDimensions("ga:pageTitle,ga:pagePath"); query.setMetrics("ga:pageviews"); query.setSort("-ga:pageviews"); query.setMaxResults(10); query.setIds(TABLE_ID);
The actual data feed request is made using the getFeed()
method
on the AnalyticsService
object.
// Make a request to the API, using DataFeed class as the second parameter. DataFeed dataFeed = analyticsService.getFeed(query.getUrl(), DataFeed.class);
Note: This is the
same method used to request data from the account feed, with one important
difference: the second parameter is the DataFeed
class.
Keep in mind that if you make requests to the data feed using the AccountFeed
class
as the second parameter, your request will succeed without error. However,
it will return the data from an AccountFeed
object, rather than
a DataFeed
object. For
this reason, you will not be able to access report data if you use the wrong
class.
If the request to the API is successful, the data is returned as a DataFeed
object.
Under the hood, XML is returned by the API.
In the example, the program iterates through each feed entry and sends the page title, URL and pageviews for that page to the system output.
// Output data to the screen. System.out.println("----------- Data Feed Results ----------"); for (DataEntry entry : dataFeed.getEntries()) { System.out.println( "\nPage Title = " + entry.stringValueOf("ga:pageTitle") + "\nPage Path = " + entry.stringValueOf("ga:pagePath") + "\nPageviews = " + entry.stringValueOf("ga:pageviews")); }
To get a sense of all the data returned from the API, read the XML data feed reference. To learn how you can access all the important data feed information, see the Java Data Feed reference example.
Error Handling
The Google Data Java Client Library throws exceptions in the following cases.
- User Login
If a user supplies an incorrect username or password, or a similar error occurs, theAuthenticationException
is thrown. If your application uses ClientLogin to authorize, and a program requests a token too frequently, the user is presented with a captcha challenge response. See more information on using ClientLogin through Google Data APIs. - Network Issues
If there is a network problem with during a request to the Google Analytics API, the IOException error is thrown. - Other Issues
The ServiceException error is thrown for a variety of other request errors. For example, if an illegal combination of dimensions and metrics is requested, you will see this error. You will also see this error if you have run out of quota. You can get the specific error code returned by using thegetCode()
on the Service Exception class. ThegetMessage()
method returns a description of the particular error.