How to Use Google Analytics API in Java
Pulling data from the Google Analytics API with Java can feel like a heavy lift, but it unlocks powerful ways to automate reporting, feed custom dashboards, or integrate site traffic data directly into your business applications. This guide will walk you through every step of the process, from generating credentials to making your first API call and parsing the results. We’ll cover authentication, building requests, and handling the response to get the exact data you need.
Preparing Your Google Cloud & Analytics Environment
Before writing any Java code, you need to set up your Google project to allow your application to securely access your Google Analytics data. This involves creating a service account, which acts like a robotic user specifically for your program.
1. Enable the Google Analytics Data API
First, you need to tell Google that you intend to use this specific API.
- Navigate to the Google Cloud Console.
- Select or create a project. If you're starting from scratch, a new project is fine.
- In the search bar at the top, type "Google Analytics Data API" and select it from the results.
- Click the Enable button. If it's already enabled, you're all set.
2. Create a Service Account
A service account provides an identity for your application, allowing it to authenticate with Google's services without needing a human user to log in.
- In the Google Cloud Console, navigate to IAM & Admin > Service Accounts.
- Click + Create Service Account at the top of the page.
- Give your service account a descriptive name (e.g., "GA Reporter Java App") and an optional description. The Service account ID will be generated automatically. Click Create and Continue.
- You don't need to grant this service account a specific role in this step, so you can click Continue.
- Similarly, you can skip the "Grant users access to this service account" step. Click Done.
3. Generate and Download JSON Credentials
Now that the service account exists, you need to create a private key that your Java application will use to prove its identity.
- Find the service account you just created in the list and click on it.
- Go to the Keys tab.
- Click Add Key and select Create new key.
- Choose JSON as the key type and click Create.
A JSON file containing your service account's private key will be automatically downloaded. Treat this file like a password. Keep it secure and never commit it to a public version control repository like GitHub.
4. Grant Access in Google Analytics
Your service account has an identity, but it doesn’t have permission to view your website's data yet. You need to "invite" it to your Google Analytics property.
- Open your newly downloaded JSON key file. Find the value associated with the
"client_email"key. It will look something likega-reporter-java-app@your-project-id.iam.gserviceaccount.com. Copy this email address. - Go to your Google Analytics account.
- Navigate to the Admin section (the gear icon in the bottom-left).
- In the Property column, select the property you want to access and click on Property Access Management.
- Click the blue + icon in the top right to add a user.
- Paste the service account's email address into the Email address field.
- Under Permissions, assign the role of Viewer. This is sufficient for reading data.
- Click Add.
With the setup complete, you're ready to move on to the Java project itself.
Setting Up Your Java Project
You'll need to add the official Google Analytics Data Client Library for Java to your project. The easiest way to manage this is with a build tool like Maven or Gradle.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Using Maven
If you're using Maven, add the following dependencies to your pom.xml file within the <dependencies> block:
<!-- Google Analytics Data API Client -->
<dependency>
<groupId>com.google.analytics</groupId>
<artifactId>google-analytics-data</artifactId>
<version>0.41.0</version> <!-- Check for the latest version -->
</dependency>
<!-- Handles Authentication -->
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.23.0</version> <!-- Check for the latest version -->
</dependency>Using Gradle
For Gradle projects, add these lines to your build.gradle file's dependencies block:
// Google Analytics Data API Client
implementation 'com.google.analytics:google-analytics-data:0.41.0' // Check for the latest version
// Handles Authentication
implementation 'com.google.auth:google-auth-library-oauth2-http:1.23.0' // Check for the latest versionAfter adding the dependencies, refresh your project to ensure they are downloaded.
Authenticating Your Application
The client library needs to find and use your service account's JSON key file to authenticate. The recommended way to do this is by setting an environment variable.
Set an environment variable named GOOGLE_APPLICATION_CREDENTIALS to the full path of the JSON key file you downloaded. For example:
- On macOS/Linux:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json" - On Windows: Use the "Edit the system environment variables" control panel to add a new variable.
When you run your Java application, the Google client library will automatically detect this environment variable and use the specified key file for authentication. This approach is more secure than hard-coding the file path directly in your code.
Making Your First API Request
Now for the fun part: writing the code to query the API. To make a request, you need to define four key components:
- Property ID: The unique ID for the Google Analytics property you want data from. You can find this in GA Admin under Property Settings.
- Dimensions: The attributes of your data. Think of them as the "rows" in your report, like
country,pagePath, orfullPageUrl. - Metrics: The quantitative measurements. These are the "columns," like
sessions,activeUsers, orconversions. - Date Ranges: The time period for your query.
Here’s a complete Java example that pulls the number of active users per country for the last 30 days.
import com.google.analytics.data.v1beta.*,
import java.io.IOException,
public class BasicAnalyticsReport {
public static void main(String[] args) throws IOException {
// Find your property ID in Google Analytics Admin > Property Settings
String propertyId = "YOUR_GA4_PROPERTY_ID",
runReport(propertyId),
}
public static void runReport(String propertyId) throws IOException {
// Using a try-with-resources statement to automatically close the client
try (AnalyticsDataClient analyticsDataClient = AnalyticsDataClient.create()) {
// Build the request object
RunReportRequest request = RunReportRequest.newBuilder()
.setProperty("properties/" + propertyId)
.addDimensions(Dimension.newBuilder().setName("country"))
.addMetrics(Metric.newBuilder().setName("activeUsers"))
.addDateRanges(DateRange.newBuilder().setStartDate("30daysAgo").setEndDate("today"))
.build(),
// Make the API call
RunReportResponse response = analyticsDataClient.runReport(request),
// Process and print the response
printReportResponse(response),
}
}
// Helper function to print the API response
public static void printReportResponse(RunReportResponse response) {
System.out.println("Report result:"),
// Print column headers
for (DimensionHeader header : response.getDimensionHeadersList()) {
System.out.printf("%-30s", header.getName()),
}
for (MetricHeader header : response.getMetricHeadersList()) {
System.out.printf("%-20s", header.getName()),
}
System.out.println(), // New line
// Print rows
for (Row row : response.getRowsList()) {
for (DimensionValue dimensionValue : row.getDimensionValuesList()) {
System.out.printf("%-30s", dimensionValue.getValue()),
}
for (MetricValue metricValue : row.getMetricValuesList()) {
System.out.printf("%-20s", metricValue.getValue()),
}
System.out.println(), // New line
}
}
}Make sure to replace "YOUR_GA4_PROPERTY_ID" with your actual GA4 property ID. When you run this code, it will print a simple table to your console showing the number of active users for each country.
Advanced Techniques & Best Practices
Once you’ve mastered the basic report, you can begin to customize your queries for more specific insights.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Filtering Your Results
You can filter your data based on dimension or metric values. For example, if you only want to see data for Canada and the United States, you can add a dimensionFilter to your request. This is much more efficient than fetching all the data and filtering it in your Java code.
To do this, you would modify the RunReportRequest object:
FilterExpression countryFilter = FilterExpression.newBuilder()
.setInListFilter(
Filter.InListFilter.newBuilder()
.addValues("United States")
.addValues("Canada")
).build(),
RunReportRequest request = RunReportRequest.newBuilder()
.setProperty("properties/" + propertyId)
.addDimensions(Dimension.newBuilder().setName("country"))
.addMetrics(Metric.newBuilder().setName("activeUsers"))
.setDimensionFilter(
FilterExpression.newBuilder()
.setFilter(
Filter.newBuilder()
.setFieldName("country")
.setInListFilter(
Filter.InListFilter.newBuilder()
.addValues("United States")
.addValues("Canada")
)
)
)
.addDateRanges(DateRange.newBuilder().setStartDate("30daysAgo").setEndDate("today"))
.build(),Handling Pagination
The API can return a maximum of 100,000 rows per request. If your report contains more data, you'll need to paginate through the results. You can do this by using the limit and offset parameters in your request.
Managing API Quotas
The Google Analytics Data API has quotas on how many requests you can make per hour and per day. These are generally generous for most applications, but it's important to be aware of them. If you're building a high-traffic application, consider implementing caching or making fewer, larger requests instead of many small ones.
Proper Error Handling
Network issues or invalid requests can happen. Always wrap your API calls in a try-catch block to gracefully handle potential ApiException errors. This allows you to log the error and prevent your application from crashing.
Final Thoughts
In this guide, we covered the end-to-end process of pulling Google Analytics data using Java. By setting up a service account, configuring your dev environment, building a targeted request, and parsing a response, you can begin to programmatically access your most important marketing data and integrate it into any system you need.
For some, managing API clients, handling authentication, and writing code is the right path. However, if this process seems too time-consuming, or if you prefer a no-code alternative, tools like Graphed can save you considerable development time. Instead of working with APIs directly, we provide one-click integrations with services like Google Analytics. You can connect your marketing and sales data sources in seconds and use simple, natural language prompts to build real-time dashboards and reports - no code required.
Related Articles
How to Create Facebook Ads API for Claude Code
Create a Meta Marketing API access token that never expires, using a system user, so Claude Code can pull Facebook ad reports and manage campaigns.
ClickHouse vs Postgres: When to Switch to Columnar
Comparing ClickHouse vs PostgreSQL means matching storage architecture to workload. Row storage wins for transactions. Columnar wins for scan-heavy analytics.
Google Ads for Orthodontists: Get More Booked Consults
Most orthodontic Google Ads campaigns waste money on low-intent searches. The problem is structure, not the platform.