Reporting API with Java 2


Google Analytics
Are you working on an application that needs to access Google Analytics data. Would you like to extract your Google analytics data? The Google Analytics Reporting API allows us to do just that. Once we are authenticated we can access a users Google Analytics data. In this tutorial I am going to show you how to extract Google analytics data using an installed java application. [wp_ad_camp_3]

Prerequisite

You will need to create a project on Google developer console. Enable the reporting API and create Oauth2 credentials to run this code. Download the credentials.json file.

Dependencies

We will need the following dependence in our application.


    compile 'com.google.apis:google-api-services-analyticsreporting:v4-rev114-1.22.0'
    compile group: 'com.google.oauth-client', name: 'google-oauth-client-jetty', version: '1.11.0-beta'

Authentication

Google Analytics data is private user data in order to access it we must request access of the user, by authenticating our application. When this method is run a web browser will open requesting access to the user Google Analytics data. We are only asking for read only access, it is best to only request the permissions that you actually need. The users authentication will be stored on the local pc so that the user will not need to authenticate again.


    /** Authorizes the installed application to access user's private data.
     *  client_secrets.json can be downloaded from Google developer console.
     *
     *  Make sure to enable the Google Analytics reporting api and create Oauth2 credentials.
     * */
    private static Credential authorize() throws Exception {
        // load client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(GoogleAnalyticsReportingSample.class.getResourceAsStream("/client_secrets.json")));

        // set up authorization code flow
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, JSON_FACTORY, clientSecrets,
                Collections.singleton(AnalyticsReportingScopes.ANALYTICS_READONLY)).setDataStoreFactory(
                dataStoreFactory).build();
        // authorize
        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

Requesting Data

Once we are authenticated we can request data. Please check the dimension and metric reference for a full list of all the dimensions and metrics that can be used with the Google Analytics API.


    /** Fetching the data from Google Analytics and returning the response*/
    public static GetReportsResponse fetchData(AnalyticsReporting service) throws IOException{

        DateRange dateRange = new DateRange();
        dateRange.setStartDate("2017-06-11");
        dateRange.setEndDate("2017-06-13");

        // 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("ga:78110423")
                .setDateRanges(Arrays.asList(dateRange))
                .setDimensions(Arrays.asList(browser))
                .setMetrics(Arrays.asList(sessions));

        ArrayList requests = new ArrayList();
        requests.add(request);

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

        // Call the batchGet method.
        return service.reports().batchGet(getReport).execute();
    }

Full Script


[wp_ad_camp_5]

Conclusion

You should now know how to authenticate an installed application using Oauth2 with java. Once you are authenticated you will be able to access the users Google Analytics data. There are additional samples for using the Google Analytics Reporting API with java on the Google Analytics website.


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

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

2 thoughts on “Reporting API with Java