Management API - Java

The Google Analytics Management API provides five separate read-only feeds
that allow your application to access Google Analytics account and configuration
data. Your application can use the Java client library to access these feeds.
For example, if your application needs a list of views (profiles) for a user, it can
request the View (Profile) Feed. Similarly, if your application needs all the goal
configuration data, including goal names for a particular view (profile), it can request
the Goal Feed.

Overview

This document covers how to use Java to access Google
Analytics data with the Google Analytics Management 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 the Google Analytics management model, each user can have a number of accounts,
web properties, views (profiles), goals, and segments. The API provides a
separate feed for each of these data types.
Once you've authorized access to the API, you follow these steps to get data
from either of these feeds:

Create a query to define the data you want to extract
through the Google Analytics Management API.

Request data by calling the getFeed method
on an authorized AnalyticsService object.

Use the helper classes from the client library to handle the data returned
from the API request.

Setting up Your Environment

The Java client library simplifies retrieving Analytics data
by handling authorization tokens and by returning Analytics data from the
Management API in Java objects. You can get the Java client
library for the Analytics Management API in one of two ways:

All calls to the Google Analytics API happen through the
AnalyticsService object. Initializing an
AnalyticsService is as easy as calling the constructor with the
client application's name sent along as a parameter.

// Service Object to work with the Google Analytics Management API.
AnalyticsService analyticsService = new AnalyticsService("XTREME Sample App!");

Now that the service object has been instantiated, it's time to authenticate.

Authorizing requests

Before users can view their account information on the Google Analytics web site,
they must first login in with a Google Account. In the same way, when users first
access your application, they will need to authorize your application to access their data.
The authorization in the API works using tokens.

Every request your application sends to the Google Analytics API must include an authorization token. The token also identifies your application to Google.

About authorization protocols

Your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported. If your application uses Google Sign-In, some aspects of authorization are handled for you.

Authorizing requests with OAuth 2.0

All requests to the Google Analytics API must be authorized by an authenticated user.

The details of the authorization process, or "flow," for OAuth 2.0 vary somewhat depending on what kind of application you're writing. The following general process applies to all application types:

When you create your application, you register it using the Google API Console. Google then provides information you'll need later, such as a client ID and a
client secret.

Activate the Google Analytics API in the Google API Console. (If the API isn't listed in the API Console, then skip this step.)

When your application needs access to user data, it asks Google for a particular scope of access.

Google displays a consent screen to the user, asking them to authorize your application to request some of their data.

If the user approves, then Google gives your application a short-lived access token.

If Google determines that your request and the token are valid, it returns the requested data.

Some flows include additional steps, such as using refresh tokens to acquire new access tokens. For detailed information about flows for various types of applications, see Google's OAuth 2.0 documentation.

Here's the OAuth 2.0 scope information for the Google Analytics API:

Scope

Meaning

https://www.googleapis.com/auth/analytics.readonly

Read-only access to the Analytics API.

To request access using OAuth 2.0, your application needs the scope information, as well as
information that Google supplies when you register your application (such as the client ID and the
client secret).

Tip: The Google APIs client libraries can handle some of the authorization process for you. They are available for a variety of programming languages; check the page with libraries and samples for more details.

Before users can view reports on the Google Analytics report interface, they
must first log in with valid a Google Account. In the same way, your Java application
must provide user access to Analytics. To do this, it must use the setUserCredentials() method
on the AnalyticsService object,
which handles all interaction between the Google Data API Java Library
and the Analytics Management API.

With the AnalyticsService object, your application can authorize
with one of three different methods:

Once your application handles authentication, it can retrieve the list of
accounts that your users have access to. The account feed is a top-level entity
in the Management API and contains
information about all the Google Analytics accounts available to the
authenticated user. In this example, the printFirstAccount() method
constructs an account feed query using the max-results URL parameter
to set the maximum records returned to 1.

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 successful response, the getFeed() method
returns all the account feed data as a ManagementFeed object.
Under the hood, the actual data being requested from the API is returned
as an AtomPub XML feed and the client library takes care of parsing the XML
into an object.

// Make request to the API, using ManagementFeed class as the second parameter.
ManagementFeed accountsFeed = analyticsService.getFeed(queryUrl, ManagementFeed.class);

The ManagementFeed object contains a collection of
ManagementEntry objects. This code example retrieves the first
entry in the account feed and prints the account name and account ID to the
system output.

In addition, each account object contains an AnalyticsLink
object that provides information about the child feed of this account —
that is, the feed of all web properties connected to the account
represented by the ManagementEntry. The following code gets that
link and pulls information about the child feed.

The web property feed returns information about the all the web properties
for the authenticated user. The web property feed is child of an account entry.
Each web property entry is a parent of a view (profile) feed. This URL will return
a feed of all web properties available to the logged-in user.

Note: This is the exact same URL you would get
by calling getHref() on this account's child link as shown in
the account example above. The purpose is only to illustrate different
ways to obtain web property data. There's no need to construct this URL yourself.

The following code calls a ManagementEntry object representing
a single web property and prints details about that web property to the screen.

The view (profile) feed returns all the Google Analytics views (profiles) for the authenticated
user. This feed is important because it provides the tableId for
each view (profile). The
tableId value is used in Google Analytics Core Reporting API queries—specifically the ids
query parameter—to identify which view (profile) to retrieve data from.

The view (profile) feed is a child of a web property entry and each view (profile) entry
is a parent of a goal Feed. To learn more about views (profiles), see the Views (Profiles)
section of the Accounts and Views (Profiles) document.

The following code constructs a ManagementFeed containing all
view (profile) entries accessible from the requested account.

// Construct query from a string.
URL queryUrl = new URL(
"https://www.googleapis.com/analytics/v2.4/management/accounts/~all/webproperties/~all/profiles");
// Make request to the API, using ManagementFeed class as the second parameter.
ManagementFeed profilesFeed = analyticsService.getFeed(queryUrl, ManagementFeed.class);

Like before, you can filter which views (profiles) will be displayed by specifying an account ID and a web property ID in place of the ~all identifier for your request. Also, you can get the URL for a feed of all views (profiles) under a specific web property by following the child link from that web property.

The goal feed provides a quick way to access all the configured goal
information for a particular view (profile). This feed is important because it provides
access to goal names, goal types and goal status (active or inactive). The goal
feed is a child of a view (profile) feed entry. Goal entries have no children.

Retrieving a ManagementFeed for goals is the same as retrieving
one for accounts, web properties, or views (profiles). Just construct the URL and
make the request:

// Construct query from a string.
URL queryUrl = new URL(
"https://www.googleapis.com/analytics/v2.4/management/accounts/~all/webproperties/~all/profiles/~all/goals");
// Make request to the API, using ManagementFeed class as the second parameter.
ManagementFeed goalsFeed = analyticsService.getFeed(queryUrl, ManagementFeed.class);

For this type of entity, printing out the data is
slightly different than for other entities. This is because a Goal object
contains either a
Destination or an Engagement object, depending on what
type of Goal it is. Each of these objects has different corresponding
data. As such, the code required to run through every possibility and print
out the relevant data differs than that for other management entities.

The segment feed provides a listing of all the default and user
created segments. A developer can then retrieve the ID of these
segments and use them in the segment
parameter of the Core Reporting API Data
Feed request. Unlike the other feeds of the management API, this feed has no
parent or child relationships.

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, the 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.

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 the getCode() on
the Service Exception class. The getMessage() method returns
a description of the particular error.