How to Get Google Analytics Data Using API

Cody Schneider8 min read

Pulling your data directly with the Google Analytics API gives you the raw ingredients to build custom reports, automate your monitoring, and blend website analytics with other business data. This tutorial will walk you through exactly how to set up access and start fetching your Google Analytics 4 data using the API.

GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

Why Use the Google Analytics API?

The standard Google Analytics interface is great for day-to-day exploration, but sometimes you need to go deeper or work with your data in another environment. The API is your key to unlocking this flexibility.

  • Custom Dashboards: Build reports with the exact metrics, dimensions, and visualizations you need in a tool like Looker Studio, Power BI, or even a custom web app. You aren't limited by the widgets and layouts of the standard GA4 dashboard.
  • Data Integration: The real magic happens when you combine data. You can pull GA data and merge it with information from your CRM (like Salesforce), your ad platforms (like Facebook Ads), and your sales data (like Shopify) to see the full customer journey.
  • Full Automation: Stop manually exporting CSVs every Monday morning. By using the API, you can write a simple script to fetch your key metrics on a schedule and send them to a spreadsheet, database, or Slack channel automatically.
  • Advanced Analysis: Gain access to more granular data for sophisticated analysis in tools like Python or R. This lets you perform custom calculations or run statistical models that aren't possible within the GA interface.

Understanding the Google Analytics APIs

The first thing to know is that there isn't just one single "Google Analytics API." The right one for you depends on which version of Google Analytics you're using. Given that Universal Analytics was sunset in July 2023, this guide will focus on the modern API for Google Analytics 4.

Google Analytics Data API: This is the current and recommended API for getting data from your Google Analytics 4 properties. If you're starting a new project, this is the one you should use.

To use this API, you'll need to understand a few basic concepts:

  • Dimensions: These are the attributes of your data - the "what." Examples include city, pageTitle, firstUserSource, or sessionCampaignName. You typically group your data by dimensions.
  • Metrics: These are the quantitative measurements - the "how many." Examples include sessions, activeUsers, conversions, and totalRevenue.
  • Date Ranges: This defines the time period you want to retrieve data for. You can use specific dates (e.g., "2024-01-01" to "2024-01-31") or relative dates (e.g., "yesterday" or "7daysAgo").
  • Filters: Filters let you narrow down your data to only include (or exclude) specific criteria, like looking at traffic only from a certain country or from a specific marketing campaign.

Getting Started: Your API Prerequisites

Before you can pull any data, you need to set up your credentials. This process involves creating a project in the Google Cloud Platform, enabling the API, and creating a special "user" called a service account that your script will use to securely access your data. Here’s a step-by-step guide.

GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

Step 1: Confirm You Have GA Access

You must have at least "Viewer" permissions for the Google Analytics property you want to access. If you aren't an admin, check with your team to make sure you have been granted access.

Step 2: Create a Google Cloud Project

All of Google's APIs are managed through the Google Cloud Platform (GCP). Even if you're not using any other cloud services, you'll need to create a project to manage API access.

  1. Go to the Google Cloud Console.
  2. If it's your first time, you'll need to agree to the terms of service.
  3. In the top header bar, click the project dropdown menu (it might say "Select a project") and click "New Project."
  4. Give your project a descriptive name (e.g., "My Website Analytics Reporting") and click "Create."

Step 3: Enable the Google Analytics Data API

Out of the box, all APIs are turned off. You need to explicitly enable the Google Analytics Data API for your new project.

  1. Within your new project in the Google Cloud Console, navigate to the search bar and look for "APIs & Services".
  2. On this dashboard, you will have the option to enable APIs and services. Look for a large "+ ENABLE APIS AND SERVICES" at the top of the dashboard.
  3. In the API Library search bar, type "Google Analytics Data API" and select its tile from the search results.
  4. Click the blue "Enable" button.

Step 4: Create a Service Account

Now, you need to create your credentials. This is done by creating a service account, which acts like a robot user that your application will use to authenticate with Google's servers. You don’t need it for yourself, just the application accessing the account.

  1. In the Google Cloud Console, navigate to "APIs & Services," then "Credentials".
  2. Click "+ CREATE CREDENTIALS" at the top and select "Service account."
  3. Give the service account a name (e.g., "ga-api-reader") and a description, then click "CREATE AND CONTINUE."
  4. For the "Grant this service account access to project" step, you can just click "CONTINUE" as we will grant GA permissions directly.
  5. Click "DONE."

Your service account is created, but you aren’t done. You now need a key file for this. This file is like a password, so be sure not to share it publicly. A JSON file will need to be downloaded from the account.

  1. On the Credentials screen, find the service account you just created in the list and click on its email address.
  2. Click on the "KEYS" tab.
  3. Click "ADD KEY" then "Create new key."
  4. Select "JSON" as the key type and click "CREATE." A JSON file will automatically download to your computer.

Important: Treat this JSON file like a password. It contains the key that grants access to your service. Store it securely and never commit it to a public code repository.

GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

Step 5: Grant Access in Google Analytics

You have everything downloaded, and just a final piece is needed. The final step is to tell Google Analytics to allow this new service account to read your property's data.

  1. Open the .json file locally that you previously downloaded. Copy the service account's client email address from your JSON file (the value associated with the client_email key).
  2. Go to your Google Analytics property, then click "Admin" (the gear icon at the bottom left).
  3. In the "Property" column, click "Property Access Management."
  4. Click the blue "+" icon in the top right and select "Add users."
  5. Paste the service account's email address into the text field.
  6. Leave all the other advanced settings as-is — they may be hard to rollback if you don’t fully understand the settings they impact. The standard settings are appropriate for most applications. Then, assign it the "Viewer" role. No other permissions are needed.
  7. Click "add".

That's it! Your setup is now complete, and you’re prepared to create the necessary scripts for execution!

Pulling Your First Report with Python

With the setup complete, let's write a simple Python script to fetch a report on the number of active users per country over the past week. First, you'll need to install the Google client library.

Open your terminal or command prompt and run:

pip install google-analytics-data

Now, create a new Python file and use the following code. Make sure to replace YOUR_KEY_FILE_PATH.json with the path to the JSON key file you downloaded and YOUR_PROPERTY_ID with the GA4 property ID for the system.

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

# Step 1: Set Your File Path and Property ID
# Replace "YOUR_KEY_FILE_PATH.json" with the path to your credentials file.
KEY_FILE_LOCATION = "YOUR_KEY_FILE_PATH.json"

# Replace "YOUR_PROPERTY_ID" with your actual GA4 Property ID.
PROPERTY_ID = "YOUR_PROPERTY_ID"


# Step 2: Initialize the client using your service account credentials
try:
    client = BetaAnalyticsDataClient.from_service_account_json(KEY_FILE_LOCATION)
    print("Authentication successful.")

    # Step 3: Define your report request
    request = RunReportRequest(
        property=f"properties/{PROPERTY_ID}",
        # Define the dimensions you want to see (e.g., country)
        dimensions=[Dimension(name="country")],
        # Define the metrics you want to count (e.g., active users)
        metrics=[Metric(name="activeUsers")],
        # Define the date range for your report
        date_ranges=[DateRange(start_date="7daysAgo", end_date="today")],
    )

    # Step 4: Run the report and get the response
    print("Running report...")
    response = client.run_report(request)
    print("Report complete.")

    # Step 5: Parse and print the response
    print("\n-- REPORT --")
    for row in response.rows:
        country=row.dimension_values[0].value
        active_users=row.metric_values[0].value
        print(f"Country: {country}\nActive Users: {active_users}\n{'-'*20}")

except Exception as e:
    print(f"An error occurred: {e}")

Run this script, and if your setup is correct, you'll see a printed list of countries and their corresponding number of active users from the last seven days!

GraphedGraphed

Still Building Reports Manually?

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

Watch Graphed demo video

Final Thoughts

Working with the Google Analytics API opens up endless possibilities for custom reporting and automation. By setting up a project and authenticating via a service account, you can combine your GA data with any system, automate tedious tasks, and build dashboards tailored perfectly to your business needs.

As you can see, this process requires careful setup, managing credential files, and writing code, which is precisely a big factor we think about when designing our features. When you use Graphed, you simply connect your Google Analytics account via a simple one-click authentication - no cloud projects, JSON keys, or Python scripts required. We manage the secure API connection for you so you can ask for the data you need to start making informed decisions.

Related Articles