Search code examples
javagoogle-analyticsgoogle-apigoogle-analytics-apiservice-accounts

Google Analytics 4 - simple example of service account API usage in Java?


I've spent a few days trying to get an example of how to do the above - use a service account to non-interactively get Google Analytics metrics using the GA4 API from Java.

The official example at

https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-java#3_setup_the_sample

has a requirement that you need to provide a "view ID" when initializing the GA4 client classes.

Nowhere can I find a "view ID" -anywhere- in my GA4 profile. I do have the JSON file with my credentials, have connected the GA4 property, created a service account, etc.

View IDs seems to be something used previously with Universal Analytics, which was discontinued 1 July 2023.

Additionally, what is the difference between "Reporting" and "Data" APIs in Google Analytics?

I've also found an official Google example of the "Data" API at

https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries

but there is a step that refers to setting an environment variable to define where to find the authentication JSON file - but where / how is an environment variable set in a headless JAR that will run on a different machine than where the JAR is being compiled (headless Linux server)?

How can I set the credentials JSON file location in the code (NOT an environment variable) per the data API example?

Trying to accomplish this in a Java Spring Maven App in NetBeans.

Thanks


Solution

  • Try this.

    GoogleCredential gc = GoogleCredential.FromStream(Utility.GetStreamFromResourceFile("C:\\Development\\FreeLance\\GoogleSamples\\Credentials\\credentials.json", GetType()));
    BetaAnalyticsDataSettings betaAnalyticsDataSettings =       BetaAnalyticsDataSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(gc)).build();
    BetaAnalyticsDataClient betaAnalyticsDataClient =      BetaAnalyticsDataClient.create(betaAnalyticsDataSettings);