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.
Hello Linda, I’m currently tryin to find all active youtube channels day by day.
Forexample:
My Get String is : https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&publishedAfter=2009-01-01T00%3A00%3A00Z&publishedBefore=2009-01-02T00%3A00%3A00Z&type=channel&key={API}
It returns me totalResults 1000000 resultsPerPage 50
but the problem is when i try to surf on nextPages by pageToken, i only can go for 3 more pages. There have to be more than 150 channels created in a day. I’m %100 sure about it.
Can anyone please help me with a solution or a better string?
Thank you, king regards.
I have seen this before. I think you should post your code on stackoverflow. I have been wondering if Google has started to limit the requests more.