How to Access Google Analytics API
Manually pulling the same reports from Google Analytics every week is a universal task for marketers. You log in, navigate the same menus, apply the same filters, and export the same CSVs just to keep an eye on performance. This article will show you how to cut out that repetitive work by programmatically connecting to the Google Analytics API, empowering you to automate your reporting and get straight to the insights.
What is the Google Analytics API and Why Should You Use It?
Think of an Application Programming Interface (API) as a secure doorway that lets different software applications talk to each other. The Google Analytics API is simply a doorway that allows your custom scripts, dashboards, or other tools to directly access your GA4 data without you needing to interact with the web interface.
Instead of manually downloading a report, your code makes a "request" to the API asking for specific data (e.g., sessions and conversions by landing page for the last 30 days), and the API sends a "response" with the raw, structured data. This opens up a world of possibilities that solve common reporting frustrations.
Here’s why it’s a game-changer:
- Automate Your Reporting: Schedule scripts to run daily, weekly, or monthly to update spreadsheets, refresh dashboards, or populate client reports. For an SEO consultant in London managing multiple local clients, this means you can build a custom dashboard that updates performance for all clients automatically every Monday morning.
- Integrate Your Data: Pull your analytics data into other business systems. You can pipe GA performance metrics directly into a CRM like Salesforce, a Google Sheet, or a BI tool like Power BI to get a complete view of your funnel.
- Bypass Interface Limitations: The standard GA4 interface sometimes uses data sampling on large reports, which can obscure the real numbers. API queries can often return unsampled data, giving you a more accurate picture of performance. You can also pull more complex combinations of dimensions and metrics than the interface allows.
- Build Truly Custom Visualizations: While the GA4 is highly customizable, the API gives you limitless control. You can build bespoke dashboards that display data exactly how your team or clients need to see it, combining metrics from GA with data from other sources like Google Ads or your e-commerce platform.
Choosing the Right Google Analytics API
When you start digging in, you'll see a few different Google Analytics APIs mentioned online. Let's clear up the confusion - for virtually all reporting needs today, you'll be using one primary API.
- Google Analytics Data API (for GA4): This is the current and primary API for fetching report data from Google Analytics 4 properties. If you're building a report, dashboard, or fetching performance metrics, this is the one you need.
- Google Analytics Admin API (for GA4): This API is for programmatic administration. You'd use this to manage users, accounts, or property settings with code, not for pulling performance data.
- Google Analytics Reporting API v4 (Deprecated): This was a very popular API for fetching data from the older Universal Analytics. Since Universal Analytics stopped processing new data, this API is now effectively legacy. If you're starting a new project, focus exclusively on the GA4 Data API.
For the rest of this tutorial, we will focus on accessing the GA4 Data API, which is what you’ll use to automate your SEO reports.
Your Step-by-Step Guide to Accessing the GA4 Data API
Getting access requires a few one-time setup steps in the Google Cloud Platform. While it looks technical at first, it’s a straightforward process you only have to do once. Follow these steps carefully, and you’ll be ready to make your first data request.
Step 1: Create a Google Cloud Platform (GCP) Project
Google manages all its APIs through the Google Cloud Platform (GCP). To use one, you first need a project to attach it to.
- Go to the Google Cloud Console and sign in with your Google account.
- In the top blue bar, next to the "Google Cloud" logo, click the project dropdown menu.
- A dialog will appear. Click on "NEW PROJECT."
- Give your project a descriptive name (e.g., "GA4 Reporting Automation") and click "CREATE." Make sure the project is selected after it's created.
Step 2: Enable the Google Analytics Data API
Now that you have a project, you need to "turn on" the specific API you want to use within it.
- In the Cloud Console dashboard, use the search bar at the top to search for "Google Analytics Data API".
- Select it from the search results marketplace page.
- On the API’s main page, click the blue "ENABLE" button. This may take a moment to provision.
Once enabled, your project now has permission to access this API.
Step 3: Create Service Account Credentials
To access the API without you personally logging in every time, you need secure credentials for your script or application. This is handled through a "service account" - a special type of non-human user designed for server-to-server communication.
- In the Cloud Console's left-hand navigation menu, go to APIs & Services » Credentials.
- At the top of the page, click "+ CREATE CREDENTIALS" and select "Service Account" from the dropdown.
- Give your service account a name (e.g., "ga4-reports-bot") and a description, then click "CREATE AND CONTINUE."
- You can skip adding a role on the next page for now. Just click "CONTINUE," then "DONE."
- You'll now see your service account listed. To generate the password file (a JSON key), click on the email address of the service account you just created.
- Go to the "KEYS" tab at the top.
- Click "ADD KEY," select "Create new key," and choose JSON as the key type.
- Click "CREATE." A JSON file containing your private key will immediately download to your computer.
Important: Treat this JSON file like a password. Do not share it publicly or commit it to a public code repository. Store it securely where your application can access it.
Step 4: Grant the Service Account Access to Google Analytics
Finally, just like a human team member, your new service account needs permission to view your Google Analytics data.
- Open the JSON file you just downloaded. Find the value for "client_email" and copy it. It will look like a long email address ending in
gserviceaccount.com. - Go to your Google Analytics account.
- Click on "Admin" (the gear icon) in the bottom-left corner.
- Make sure you have the correct Account and Property selected, then in the property column, click on "Property Access Management."
- Click the blue "+" icon in the top right and select "Add users."
- Paste the service account email address into the "Email address" field.
- By default, "Viewer" is selected as the role. For data retrieval, this is the perfect level of permission - it grants read-only access but cannot make any changes. Click "Add."
That's it! Your setup is complete. You now have everything you need to start pulling your analytics data programmatically.
Making Your First API Request: An Example with Python
With permissions set up, let's pull some actual data. Python is a popular choice for data analysis and is well-supported by Google's client libraries. The following script shows you how to pull the number of sessions and users per country in the last week.
First, you'll need to install the Google client library:
pip install google-analytics-dataThen, create a Python file (e.g., report.py) and use the following code. Remember to replace YOUR_PROPERTY_ID with your actual GA4 Property ID and point the KEY_FILE_LOCATION to the JSON key you downloaded.
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 downloaded JSON key file
KEY_FILE_LOCATION = "/path/to/your/credentials.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = KEY_FILE_LOCATION
# Set your GA4 Property ID
PROPERTY_ID = "YOUR_PROPERTY_ID_HERE"
def run_simple_report():
"""Runs a simple report on a Google Analytics 4 property."""
client = BetaAnalyticsDataClient()
request = RunReportRequest(
property=f"properties/{PROPERTY_ID}",
dimensions=[Dimension(name="country")],
metrics=[Metric(name="activeUsers"), Metric(name="sessions")],
date_ranges=[DateRange(start_date="7daysAgo", end_date="today")],
)
response = client.run_report(request)
print("--- Report Results ---")
for row in response.rows:
print(f"Country: {row.dimension_values[0].value}, Active Users: {row.metric_values[0].value}, Sessions: {row.metric_values[1].value}")
if __name__ == "__main__":
run_simple_report()When you run this script, it will connect to the API using your secure key and print a clean report directly in your terminal. This is just the beginning. Imagine scheduling this to run daily to monitor SEO performance for your clients in London, automatically flagging any traffic anomalies from a specific UK region.
Final Thoughts
Navigating the initial API setup can seem like a lot of steps, but it's a worthwhile one-time investment. Once connected, you unlock the ability to get your data on your terms - unconstrained by the GA interface - saving you countless hours of repetitive manual report building in the long run.
We built Graphed to make this deep level of data analysis accessible without you ever needing to touch the technical setup. Instead of generating API keys and writing Python scripts, you can connect Google Analytics in a couple of clicks. From there, you just ask questions in plain English, like "Create a dashboard comparing organic sessions versus paid sessions from London over the past 90 days." Graphed instantly builds the live, interactive visualization for you, getting you from question to insight in seconds.
Related Articles
What SEO Tools Work with Google Analytics?
Discover which SEO tools integrate seamlessly with Google Analytics to provide a comprehensive view of your site's performance. Optimize your SEO strategy now!
Looker Studio vs Metabase: Which BI Tool Actually Fits Your Team?
Looker Studio and Metabase both help you turn raw data into dashboards, but they take completely different approaches. This guide breaks down where each tool fits, what they are good at, and which one matches your actual workflow.
How to Create a Photo Album in Meta Business Suite
How to create a photo album in Meta Business Suite — step-by-step guide to organizing Facebook and Instagram photos into albums for your business page.