Search code examples
javagoogle-apigoogle-oauthgoogle-analytics-apigoogle-api-java-client

Google Analytics Reports v4 API does not show graph in browser


I have started updating with Google Analytics Reports v4 API. I have no prior knowledge. I am trying to generate a simple graph.

I have used the given sample code given in google analytics document. But I am not getting the report at all, but a message

Received verification code. You may now close this window...

No idea why such message displaying. It looks like there is no data available. So far I have done the below things to run the project.

  1. Create the project.
  2. Crate the service.
  3. Create the View with email address retrieved from service's JSON file.
  4. Create client_secrets.json and add it to my src\ folder.
  5. Get the view id and use it in my code.

I do not know which direction to go from here. There are many things to look after and the documentation is really healthy. This is difficult for a beginner like me to decide to choose the right parts.

Also, I have the below questions to know answer.

  1. Is it possible to run it on local server such as Tomcat?
  2. Is google analytics free? Can I use it using my gmail email address?
  3. Is it important to have domain and hosting to get the report in browser?
  4. Am I need to give valid return URL while setting the client settings?
  5. Why am I need to give View ID? If it is to give manually then how do I generate the report dynamically?

Here is my environment and Java code. Please review and help me to find the solution. I am looking forward to a smooth and clean guidelines.

Environment

  1. Eclipse Java EE with Tomcat 9.0.30 server.
  2. Java used as programming language.

Code

package com.garinst;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.api.services.analyticsreporting.v4.AnalyticsReportingScopes;
import com.google.api.services.analyticsreporting.v4.AnalyticsReporting;
import com.google.api.services.analyticsreporting.v4.model.ColumnHeader;
import com.google.api.services.analyticsreporting.v4.model.DateRange;
import com.google.api.services.analyticsreporting.v4.model.DateRangeValues;
import com.google.api.services.analyticsreporting.v4.model.GetReportsRequest;
import com.google.api.services.analyticsreporting.v4.model.GetReportsResponse;
import com.google.api.services.analyticsreporting.v4.model.Metric;
import com.google.api.services.analyticsreporting.v4.model.Dimension;
import com.google.api.services.analyticsreporting.v4.model.MetricHeaderEntry;
import com.google.api.services.analyticsreporting.v4.model.Report;
import com.google.api.services.analyticsreporting.v4.model.ReportRequest;
import com.google.api.services.analyticsreporting.v4.model.ReportRow;

/**
 * A simple example of how to access the Google Analytics API.
 */
public class HelloAnalytics {
    // Path to client_secrets.json file downloaded from the Developer's Console.
    // The path is relative to HelloAnalytics.java.
    private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";

    // Replace with your view ID.
    private static final String VIEW_ID = "96519128";

    // The directory where the user's credentials will be stored.
    /*
     * private static final File DATA_STORE_DIR = new File(
     * System.getProperty("user.home"), ".store/hello_analytics");
     */
    private static final File DATA_STORE_DIR = new File("hello_analytics");

    private static final String APPLICATION_NAME = "Hello Analytics Reporting";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static NetHttpTransport httpTransport;
    private static FileDataStoreFactory dataStoreFactory;

    public static void main(String[] args) {
        try {
            AnalyticsReporting service = initializeAnalyticsReporting();

            GetReportsResponse response = getReport(service);
            printResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Initializes an authorized Analytics Reporting service object.
     *
     * @return The analytics reporting service object.
     * @throws IOException
     * @throws GeneralSecurityException
     */
    private static AnalyticsReporting initializeAnalyticsReporting() throws GeneralSecurityException, IOException {

        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(HelloAnalytics.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

        // Set up authorization code flow for all authorization scopes.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
                clientSecrets, AnalyticsReportingScopes.all()).setDataStoreFactory(dataStoreFactory).build();

        // Authorize.
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        // Construct the Analytics Reporting service object.
        return new AnalyticsReporting.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
    }

    /**
     * Query the Analytics Reporting API V4. Constructs a request for the sessions
     * for the past seven days. Returns the API response.
     *
     * @param service
     * @return GetReportResponse
     * @throws IOException
     */
    private static GetReportsResponse getReport(AnalyticsReporting service) throws IOException {
        // Create the DateRange object.
        DateRange dateRange = new DateRange();
        dateRange.setStartDate("7DaysAgo");
        dateRange.setEndDate("today");

        // Create the Metrics object.
        Metric sessions = new Metric().setExpression("ga:sessions").setAlias("sessions");

        // Create the Dimensions object.
        Dimension browser = new Dimension().setName("ga:browser");

        // Create the ReportRequest object.
        ReportRequest request = new ReportRequest().setViewId(VIEW_ID).setDateRanges(Arrays.asList(dateRange))
                .setDimensions(Arrays.asList(browser)).setMetrics(Arrays.asList(sessions));

        ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
        requests.add(request);

        // Create the GetReportsRequest object.
        GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);

        // Call the batchGet method.
        GetReportsResponse response = service.reports().batchGet(getReport).execute();

        // Return the response.
        return response;
    }

    /**
     * Parses and prints the Analytics Reporting API V4 response.
     *
     * @param response the Analytics Reporting API V4 response.
     */
    private static void printResponse(GetReportsResponse response) {

        for (Report report : response.getReports()) {
            ColumnHeader header = report.getColumnHeader();
            List<String> dimensionHeaders = header.getDimensions();
            List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
            List<ReportRow> rows = report.getData().getRows();

            if (rows == null) {
                System.out.println("No data found for " + VIEW_ID);
                return;
            }

            for (ReportRow row : rows) {
                List<String> dimensions = row.getDimensions();
                List<DateRangeValues> metrics = row.getMetrics();
                for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
                    System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
                }

                for (int j = 0; j < metrics.size(); j++) {
                    System.out.print("Date Range (" + j + "): ");
                    DateRangeValues values = metrics.get(j);
                    for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
                        System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k));
                    }
                }
            }
        }
    }
}

Maven Dependencies

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>1.30.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client-gson -->
    <dependency>
        <groupId>com.google.api-client</groupId>
        <artifactId>google-api-client-gson</artifactId>
        <version>1.30.7</version>
    </dependency>
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-analyticsreporting</artifactId>
        <version>v4-rev20190904-1.30.1</version>
    </dependency>
  </dependencies>

Solution

  • Received verification code. You may now close this window...

    This is the first step in the Oauth2 flow once the user has autorized your access to their google analytics data this code is returned to your application which is then exchanged for an access token. You may want to look into Oauth2 or you could just do what it says and close the window.

    Is google analytics free? Can I use it using my gmail email address?

    Yes the Google analytics api is free to use. Users login to your application with the user they have set up in their google analytics account

    Is it important to have domain and hosting to get the report in browser?

    You will need to host your application some place that users can access it. Remember google analytics returns data as Json it will be up to you to build your reports and display it to your users.

    Am I need to give valid return URL while setting the client settings?

    You will need a valid redirect uri if you are going to host this on the web in order for the authorization process to complete.

    Why am I need to give View ID? If it is to give manually then how do I generate the report dynamically?

    Users can have more then one google analytics account each account can have more then one web properly and each web property can have more then one view. Your users need to be able to decide which view they want to see data for.

    Note

    This system is for requesting data from google analytics the raw data it is returned as json. It is not returned as reports you will need to create your graphics yourself. Oauth2 login is for multi user system anyone can log in to your application its not going to just show your personal data.

    comment question

    Is there any possibility to get the dynamic result such as user will login and get his own data?

    Thats how oauth2 works. The user logs in your application has access to their data

    How is it possible to display the JSON data in graphical reports as available in google analytics?

    You will either need to create a library for graphics or find one already created for you by a third party and plug in the data you get back from Google analytics. APIs just return json data they dont have any control over how you the developer display it.