This document covers the basic steps of using Java to access your Google Analytics Data with the Google Analytics Data Export API. It assumes you have basic knowledge of the Java programming language.
You will get the most out of this document if you are familiar with the following:
In Google Analytics, each account can have any number of reporting 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 profile a user can
access in an account. Your application supplies the table ID to request data
from a particular 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:
getFeed method on an authorized AnalyticsService object.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 Data Export API in one of two ways:
Once you have your IDE set up correctly with the Google Data client libraries,
reference the following JAR files in your CLASSPATH:
gdata-core-1.0.jar gdata-client-meta-1.0.jar gdata-client-1.0.jar gdata-analytics-meta-2.0.jar gdata-analytics-2.0.jar google-collect-1.0-rc1.jar jsr305.jar
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 Data Export API.
With the AnalyticsService object, you can authorize your users
with three different methods:
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 Data Export API.
AnalyticsService analyticsService = new AnalyticsService("gaExportAPI_acctSample_v1.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:
Once your application handles authorization, it can retrieve account
data in order to determine which profiles your users have access to. In this
example, the main() method
constructs an account feed query, setting the maximum records returned to
50.
// Construct query from a string.
URL queryUrl = new URL(
"https://www.google.com/analytics/feeds/accounts/default?max-results=50");
Next, the code calls the getFeed() method on the AnalyticsService object,
passing in the queryURL as
the first parameter. The second parameter is the client library class which
contains the results returned from the feed. Upon a sucessful response, the getFeed() method
returns all the account feed data as an AccountFeed object.
Under the hood, the actual data being requested from the API is returned
as XML and the client library takes care of parsing the XML into an an object.
// Make request to the API, using AccountFeed class as the second parameter. AccountFeed accountFeed = analyticsService.getFeed(queryUrl, AccountFeed.class);
The AccountFeed object is made up of a number of objects. This
example retrieves all the entries of each feed, where each entry represents
a row of data. For each entry, the code prints the account and profile names,
and profile and table IDs to the system output.
// Output the data to the screen.
System.out.println("-------- Account Feed Results --------"); for (AccountEntry entry : accountFeed.getEntries()) { System.out.println( "\nAccount Name = " + entry.getProperty("ga:accountName") + "\nProfile Name = " + entry.getTitle().getPlainText() + "\nProfile Id = " + entry.getProperty("ga:profileId") + "\nTable Id = " + entry.getTableId().getValue()); }
To get a sense of all the data returned from the API, read the XML account feed reference. To learn how you can access all the important account feed information, look through the Java Account Feed reference example.
Once the account feed retrieves the valid table IDs for each profile, your application uses them to construct a data feed query. The data feed gets profile (report) data through the API. Because the table ID is a unique identifier for each profile, it is a required parameter in the query in order to indicate which profile to retrieve data from.
In our example, the application supplies the table ID of
the 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.
The Google Data Java Client Library throws exceptions in the following cases.
AuthenticationException 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.getCode() on
the Service Exception class. The getMessage() method returns
a description of the particular error.