Enterprise Java

Google API: How to access Analytics data?

Before we dig into Google Analytics API it is always useful to understand few of the Google Analytics jargon and their relationship .

Google Account: To access Google Analytics the user will need a Google Account which enables users to login to multiple Google products e.g. Gmail, Blogger, Analytics, Adsense etc. [user.01@gmail.com].

Google Analytics Account:When the user wants to access the features of the web analytics they will need to register for this service. This is a unique ID representing the analytics account. The user can still use their Google account email address to authenticate and login to the Analytics account services. [e.g. 65421]

Google Analytics Sample Account

Web properties: A web property can be referred to as one website which can be tracked independently. If the account is called AbcCompany then a web property can be abc.com which refers to the user’s personal website, another web property can be abcbiz.com which refers to user’s business website and other one can be abc.mobi which is specifically targeted to his mobile customers. The web properties under the account will have the same Account number but with different suffix. E.g. If the Account Id for AbcCompany is 65421 so the web property for abc.com can be UA-65421-1, for abcbiz.com it can be UA-65421-2.

Google Analytics sample property

Create a New Property using the Property tab:

Create a New Property

Google Analytics Profile: Each web property account will have at least one analytics profile. The profile has access to all the analytics data and reports. Each profile will have a unique profile Id. The profiles can have multiple Goals, Users, Filters and Assets.

Profiles

The Profile settings tab gives the details of the Profile Id and Website URL.The profile can have one or multiple users.

Edit Profile Settings

The details of the relationship is highlighted in the below diagram.

GA User Profile Account relationship

What is OAuth 2.0?

OAuth is an open standard for authorisation. It allows users to share their resources from one location to another location without the necessity to share credentials. OAuth 2.0 is based on the OAuth protocol however it helps with new authentication features for web applications, desktop applications, mobile applications etc. They use tokens instead of the actual username and password for speaking to each other and provide authorisation.

How is Google API related to OAuth2.0?

Google API provides access to their application using OAuth 2.0 standard. Google uses this protocol as their authentication and authorization especially when the third party clients want to have an access to the Google application data securely. The Google authorisation works in few high level steps:

a) Register application with Google
b) Redirect a browser to the URL
c) Parse a token from the response
d) Send the token to the Google Authorisation server.
e) Get the Google Analytics data by using the access token to the request.

The following diagram describes the steps which are followed to get authenticated and authorized to the Google Server (in this case Analytics server).

Google Analytics Architecture

Well all the introduction is now over. We will be back to action. Till now we have learnt about the various features of Google Analytics data and also about the authorisation and authentication mechanism. Now we will go into the implementation details. Oops…There is still one item missing. It’s all about what data we will be accessing from Google Analytics and how are they related.

Dimension vs Metrics

Dimension vs Metrics

In simple terms the Dimension in Google analytics represents the rows in the report and metrics represents the columns. E.g. the Dimension refers to Country, Browsers, Traffic sources and metrics refers the visits, new visitors, transactions etc.

So what are we trying to do with all these details?

Problem Statement: We are trying to create a standalone application which will try to use the OAuth 2.0 protocol and fetch the data from the Google Analytics.

Solution:

Step 1: Download and Import Jar files

To start with we will need to download and import the following jar files:
Download Location : Google client API

  • google-api-client-1.8.0-beta.jar – Contains the Core API code for the Google Analytics
  • google-oauth-client-1.8.0-beta.jar – Contains the OAuth client code
  • gson-2.1.jar – Java library to convert JSON to Java object and vice versa
  • guava-11.0.1.jar – This jar contains several Google’s core libraries e.g. collections, caching, primitive support, common annotations, string processing
  • jackson-core-asl-1.9.4.jar – This is high performance JSON processor

Step 2: Register client application with Google

Every application has to be registered with the Google API so that we can use the OAuth 2.0 token during the authentication and authorisation process. To register an application the user has to login to the Google account and go to Google API console.

In the Google API console Create a New Project using the left hand menu.

Create a New project

Using the Services tab enable the Analytics API so that it can be accessed.

Enable Analytics API

From the API Access tab create an OAuth 2.0 client ID.

Create OAuth client ID

Create Branding information for Client ID

Create Branding information

Select application type. In our example we select “Installed application” usually running on the local system.

Select Application Type

API console summary providing the details of the Client ID and Client secret.

Google API Console Summary

Step 3: Authorising Requests

The registration gives the clientId and clientSecret value for your application so that it can work with the Google API. This is keys will avoid the client application to share the username or password and instead make use of these keys.

When the client application is executed it prompts the users to allow access and redirects the users to the Google URL which in turns provides an authorisation code. The authorisation code is fed back to the client application which then uses the code to get the access token.

Step 4: Accessing the Google Analytics user data

The client application uses the access token to get the Google analytics user’s data.

<<GA Example Download Code>>

Sample Code Explanation:

The Client ID and Client Secret value received from the Google API console needs to copied here in the program.

private static final String CLIENT_ID = "XXXXXXXXXX";
private static final String CLIENT_SECRET = "XXXXXXXXX";

Generate the URL which will be used to get the authorisation code.

String authorizationUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID,
    REDIRECT_URL, SCOPE).build();

Here REDIRECT_URL refers to the absolute URI path which the authorisation server will redirect the user agent to the end user authorisation step is complete and SCOPE refers to the scope of the access request expressed. Once the application is executed the URL is generated. This URL will ask if the Analytics account user can allow the access to get the authorisation code. Once the authorisation code is generated it will be used in the client application to get an access to the Google API token.

Read the authorisation code from console:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Get an access to the OAuth 2.0 token using the authorisation code:

AccessTokenResponse response = new GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant(
     netHttpTransport, jacksonFactory, CLIENT_ID, CLIENT_SECRET,
     authorizationCode, REDIRECT_URL).execute();

Initialize the Analytics service object:

Analytics analytics = Analytics.builder(netHttpTransport, jacksonFactory)
  .setHttpRequestInitializer(googleAccessProtectedResource)
                .setApplicationName(APPLICATION_NAME).build();

Get Profile details:

Profiles profiles = analytics.management().profiles()
    .list("~all", "~all").execute();

Get Analytics data using API query:

Get apiQuery = analytics.data().ga()
 .get("ga:" + profile.getId(), // Table ID ="ga"+ProfileID
 "2012-03-21", // Start date
 "2012-05-04", // End date
 "ga:visits"); // Metrics

Set filters:

apiQuery.setFilters("ga:medium==referral");
apiQuery.setMaxResults(100);

Execute query:

GaData gaData = apiQuery.execute();

The data can then be retrieved from the GaData object using the retrieveData() method.

public static void retrieveData(GaData gaData) {
// Get Row Data
if (gaData.getTotalResults() > 0) {
// Get the column headers
for (ColumnHeaders header : gaData.getColumnHeaders()) {
System.out.format("%-20s",
header.getName() + '(' + header.getDataType() + ')');
}
System.out.println();
// Print the rows of data.
for (List<String> rowValues : gaData.getRows()) {
for (String value : rowValues) {
System.out.format("%-20s", value);
}
System.out.println();
}
} else {
System.out.println("No data available");
}
}

In case you want to know more about Google Analytics then you can refer to our article “All about Google Analytics“.

Reference: Google API: How to access Analytics data? from our JCG partner Mainak Goswami at the Idiotechie blog.

Mainak Goswami

Mainak Goswami is an experienced Technology Consultant specializing in JEE, Web Development and Open source technologies. He is currently based out of United Kingdom. He is a technology enthusiast trying to explore the latest in the world of technology. His current area of interest is Mobility, NoSQL and Cloud computing. In past time he loves blogging on his website Idiotechie.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mainak Goswami
11 years ago

Thanks to all my readers. Please feel free to let me know your comments and feedback.

Vina
Vina
9 years ago

Good one!

Elic
Elic
9 years ago
Reply to  Vina

I don’t manage to view the full post and the images – is there another version of this post?

I have to say I could not get going just by reading Google’s documents they seem to be very outdated.

Thanks

Jennfier Samuel
Jennfier Samuel
8 years ago

I can’t see images .
Can you provide me full code?
Thank you in advance.

Xavier
Xavier
8 years ago

HI,
I have this error Exception in thread “main” java.lang.NoSuchMethodError: com.google.api.client.http.UrlEncodedContent: method ()V not found , i can’t resolve it ,have you any idea how can i fix it pleaaase ?

Back to top button