How to Use the Google Analytics API

Cody Schneider8 min read

The Google Analytics interface is fantastic for a quick look at your website's performance, but what happens when you need more? Pulling your data programmatically with the Google Analytics API unlocks a world of custom dashboards, automated reporting, and deeper analysis that you simply can't do within the standard web version. This guide will walk you through what the API is, why you should use it, and how to make your first data request.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

What Exactly Is the Google Analytics API?

Think of the Google Analytics API as a secure backdoor to your analytics data. Instead of logging into the GA website and manually clicking through reports, the API (Application Programming Interface) allows your applications to 'talk' directly to Google's servers and request information automatically.

This means you can write a simple script or use a BI tool to pull specific metrics and dimensions on a schedule, without ever opening your web browser. It’s the difference between going to the library to read a book versus having the book delivered directly to your Kindle. One is a manual process bound by a specific physical interface, while the other is an automated, direct line to the information source.

Why Bother Using the API?

Working with an API might sound technical, but the benefits are well worth the initial learning curve, saving you countless hours in the long run.

  • Custom Dashboards and Reporting: You're no longer limited by the widgets and layouts inside Google Analytics. Pull your data into tools like Power BI, Tableau, Google Sheets, or a custom-built web application to visualize it exactly how you and your stakeholders want to see it.
  • Automate Your Repetitive Reporting: Tired of downloading the same CSV files every Monday morning to update your weekly performance spreadsheet? The API lets you automate this entire process. A script can fetch the latest data and populate your reports while you sleep, freeing you up to focus on analysis rather than data collection.
  • Integrate GA Data with Other Sources: This is a massive advantage. You can combine your website traffic data from GA with sales data from your CRM (like Salesforce), ad spend from Facebook Ads, and email performance from Klaviyo. This allows you to build a comprehensive view of your entire customer journey and accurately calculate metrics like cost per acquisition (CPA) and return on investment (ROI) across platforms.
  • Access More Granular Data: The API often allows for more complex queries and access to unsampled data in some cases, giving you a more accurate and deeper understanding of user behavior beyond what's available in the default reports.
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

A Quick Look at the Different Google Analytics APIs

When people talk about the "Google Analytics API," primarily for GA4, they are usually referring to the Google Analytics Data API. This is the main API you'll use for querying your report data.

To use it effectively, you need to understand three core concepts:

  • Metrics: These are the quantitative measurements - the numbers. Think of things like Sessions, Active Users, Conversions, and Total Revenue.
  • Dimensions: These are the attributes that describe your data. They provide context for your metrics. Examples include Country, Traffic Source, Device Category, and Page Title. You use dimensions to segment and slice your metrics (e.g., showing Sessions by Country).
  • Date Ranges: This one is straightforward - it’s the time period for which you want to retrieve data (e.g., the last 7 days, the last month, a specific quarter).

There are other, more specialized APIs like the Admin API (for programmatically managing users, properties, and data streams) and the Realtime Reporting API, but for building reports and dashboards, the Data API is your go-to.

Getting Started: Your Step-by-Step Guide to Accessing the API

Let's get our hands dirty. To connect to the API, you first need to set up a project in the Google Cloud Platform and create credentials that your application can use to authenticate itself.

Step 1: Create a Google Cloud Project

Every API connection needs to be associated with a project. If you don’t have one already, it’s simple to create.

  1. Go to the Google Cloud Console.
  2. At the top of the page, click the project dropdown menu and select "New Project."
  3. Give your project a descriptive name (e.g., "My Website Analytics API") and click "Create."

Step 2: Enable the Google Analytics Data API

By default, APIs are not "turned on." You need to explicitly enable the one you want to use for your project.

  1. In the Google Cloud Console, with your new project selected, navigate to the menu in the top-left and go to "APIs & Services" > "Library."
  2. In the search bar, type "Google Analytics Data API" and press Enter.
  3. Click on the result and then click the "Enable" button.

Step 3: Create Service Account Credentials

Now, we need to create a credential so your application can prove who it is. For automated, server-to-server interactions, a "Service Account" is the best method. Think of it as creating a 'robot' user that has permission to access your data.

  1. Navigate to "APIs & Services" > "Credentials."
  2. Click "+ Create Credentials" and select "Service Account."
  3. Give your service account a name (e.g., "ga-api-reporter") and an optional description. Click "Create and Continue."
  4. Skip the optional steps for granting access to the project by clicking "Continue," then "Done."
  5. You should now see the new service account in your list. Click on it.
  6. Go to the "KEYS" tab. Click "Add Key" > "Create new key."
  7. Choose "JSON" as the key type and click "Create." A JSON file containing your private key will automatically download. Treat this file like a password! Do not share it or commit it to a public code repository.

Step 4: Grant the Service Account Access in Google Analytics

Finally, you need to tell Google Analytics that your new 'robot' user is allowed to view data.

  1. Open the JSON file you just downloaded. Find the client_email address (it will look something like ga-api-reporter@your-project-id.iam.gserviceaccount.com). Copy this entire email address.
  2. Go to your Google Analytics property.
  3. Click on "Admin" (the gear icon in the bottom left).
  4. In the "Property" column, click on "Property Access Management."
  5. Click the blue "+" button in the top right and select "Add users."
  6. Paste the service account's email address into the "Email addresses" field.
  7. Do not check "Notify new users by email." For permissions, grant it the "Viewer" role. A 'viewer' can read and see data but cannot make any changes, which is perfect and secure for reporting purposes.
  8. Click the "Add" button.

That's it! Your setup is complete. You now have everything you need to start pulling data.

GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

Making Your First API Call (Python Example)

Now for the fun part. Let's use Python, a popular language for data analysis, to request the number of active users per country over the last week. First, you'll need your GA4 Property ID, which you can find in GA Admin > Property Settings.

1. Set Up Your Environment

First, you'll need to install the necessary Google Client Library for Python. Open your terminal or command prompt and run:

pip install google-analytics-data

2. Putting It All Together: The Script

Save the JSON key file you downloaded earlier into the same directory as your Python script. Rename it to a simple name like credentials.json. Then, create a Python file (e.g., report.py) and paste in the following code. Don't forget to replace 'YOUR_PROPERTY_ID' with your actual GA4 property ID.

import os
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    DateRange,
    Dimension,
    Metric,
    RunReportRequest,
)

# Set the path to your credentials file
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'credentials.json'

# Replace with your actual GA4 Property ID
PROPERTY_ID = 'YOUR_PROPERTY_ID'

def run_simple_report():
    """Runs a simple report using a service account."""
    client = BetaAnalyticsDataClient()

    request = RunReportRequest(
        property=f"properties/{PROPERTY_ID}",
        dimensions=[Dimension(name="country")],
        metrics=[Metric(name="activeUsers")],
        date_ranges=[DateRange(start_date="7daysAgo", end_date="today")],
    )

    print("Running report...")
    response = client.run_report(request)
    print("Report complete.")

    print("\n--- REPORT RESULTS ---")
    for row in response.rows:
        # Get the dimension value (country) and metric value (activeUsers) from the row
        country = row.dimension_values[0].value
        active_users = row.metric_values[0].value
        print(f"Country: {country}, Active Users: {active_users}")

if __name__ == "__main__":
    run_simple_report()
GraphedGraphed

Still Building Reports Manually?

Watch how growth teams are getting answers in seconds — not days.

Watch Graphed demo video

3. Running The Script

Simply navigate to your project directory in your terminal and run the script:

python report.py

If everything is set up correctly, you'll see a simple printout of each country and its corresponding number of active users from the last seven days — your first successful API response!

Final Thoughts

Working with the Google Analytics API is a powerful way to break free from the constraints of the web interface, allowing you to build truly custom dashboards and automate your reporting cadence. While the initial setup involves a few technical steps in Google Cloud and GA, once you're connected, you unlock a repeatable way to access your invaluable website data.

Let's be honest, though — managing API credentials, writing Python scripts, and parsing JSON responses isn't for everyone and can be a huge time-sink. We built Graphed because we knew there had to be an easier way. Instead of writing code, you can just connect your Google Analytics account with one click and use plain English to ask questions like, "Show me a chart of active users by country for the last 7 days." We handle all the API complexity in the background, instantly turning your questions into live, interactive dashboards so you can spend less time wrestling with data and more time acting on it.

Related Articles