DEV Community

Cover image for Google Analytics 4: access data via Data API (Step-by-step)
Sasireka Balasubramaniyam
Sasireka Balasubramaniyam

Posted on

Google Analytics 4: access data via Data API (Step-by-step)

If you want to build a custom report or dashboard for your Google Analytics data in your app or website, you have to use the Google Analytics Data API v1. In this beginner tutorial, you’ll learn about the OAuth process and query the GA4 property data programmatically.

Before beginning, make sure you have this:

  1. A Google Analytics account with a property set up
  2. A basic knowledge of REST APIs in Python.

Accessing GA4 data using Google Analytics Data API v1

Step 1: Create a cloud project

  1. Open the Google Cloud Console using the link https://cloud.google.com/

  2. Log in using your mail ID

  3. Click console on the top right corner and click ‘My first Project’, and create a new project with all necessary data

Creating a new project

Step 2: Create client OAuth 2.0

In this, we'll get a client ID and secret. Both datasets will be used for later authentication purposes.

  1. Search for ‘ Google OAuth Platform’ and click

  2. Click clients and click ‘Get Started’. If you are working on a new project, then it asks for project configuration and requires you to fill in all necessary data. If you are working on an old project, it’s already one. Copy the client ID and secret.

    Complete project configuration

  3. After this, go to ‘Clients’ on the same page and click ‘Create client.’ Fill in all the necessary data. Application type based on your need, name, and add a redirect URI. This link should be valid. Because your access token code will be redirected to this link only.

    Creating OAuth client 2.0

  4. Finally, your OAuth 2.0 client is created and you can download the credential file in JSON format.

    OAuth 2.0 client credentials JSON

  5. If you have any doubts about this, refer to the blog https://agentzee.ai/blogs/how-to-access-google-analytics-dashboard-data-via-api-with-an-access-token

Step 3: Enable Google Analytics Data API v1

To access the Google Analytics Data from its dashboard we need to enable the API we want to use. Here, we retrieve the data through the Google Analytics Data API v1.

  1. Search for ‘APIs and Services’ and select it

  2. Click the ‘Enable APIs and Services’ button to enable the Data API

  3. Search for ‘Google Analytics Data API’ and select it. There will be a button named ‘Enable’, and click this. Now we have enabled the required Google Analytics Data API.

Enable GA4 Data API

Step 4: Generate an access token

We did all the necessary steps.

  1. Firstly we need to generate a code to authorize the user. This code will be used later to generate a token. Its life span is so short. Replace your client Id and redirect URL from the downloaded JSON.

  2. Copy and paste the link below into your browser. It will redirect to the page, and you will get the ‘code’. Just copy and store it somewhere.

    https://accounts.google.com/o/oauth2/v2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=https://www.googleapis.com/auth/analytics.readonly&access_type=offline&prompt=consent
    

    generative authorize code

  3. Open Postman and create a new HTTPS request. Just copy the below Curl command in that and replace all your details, such as code, client ID, client secret, and redirect URI.

    curl -X POST https://oauth2.googleapis.com/token \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "code=AUTHORIZATION_CODE" \
    -d "client_id=YOUR_CLIENT_ID" \
    -d "client_secret=YOUR_CLIENT_SECRET" \
    -d "redirect_uri=YOUR_REDIRECT_URI" \
    -d "grant_type=authorization_code"
    

    Then you will get a response like this

    {
    "access_token": "ya29.a0AfH6SMA...",
    "expires_in": 3599,
    "refresh_token": "1//0gdfgsdfg...",
    "scope": "https://www.googleapis.com/auth/analytics.readonly",
    "token_type": "Bearer"
    }
    

Now we get an access token. Using this access token, we can fetch Google Analytics dashboard data through the GA4 Data API.

Step 5: Accessing data through the Data API

Here we can see how to fetch the active users’ data from the Google Analytics dashboard. Replace your access token and property ID from the Google Analytics dashboard, GA4 → Admin → Property details → Copy your property ID there.

import requests
import json

PROPERTY_ID = "YOUR_GA4_PROPERTY_ID"
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
url = f"https://analyticsdata.googleapis.com/v1beta/properties/{PROPERTY_ID}:runReport"

headers = {
    "Authorization": f"Bearer {ACCESS_TOKEN}",
    "Content-Type": "application/json"
}
payload = {
"metrics": [
        {
            "name": "activeUsers"
        }
    ],
    "dimensions": [
        {
            "name": "date"
        }
    ],
    "dateRanges": [
        {
            "startDate": "7daysAgo",
            "endDate": "today"
        }
    ]
}

response = requests.post(
    url,
    headers=headers,
    data=json.dumps(payload)
)
print("Status Code:", response.status_code)
print(json.dumps(response.json(), indent=2))
Enter fullscreen mode Exit fullscreen mode

Here, activeUsers is a valid metric to fetch active users’ data. The response will be like

    {
  "rows": [
    {
      "metric_names": [
        "activeUsers"
    ],
    "dimension_names": [
        "date"
    ],
    "start_date": "7daysAgo",
    "end_date": "today",
    "result": [
        {
            "date": "20260508",
            "activeUsers": "35"
        },
        {
            "date": "20260504",
            "activeUsers": "32"
        },
        {
            "date": "20260511",
            "activeUsers": "10"
        }
    ]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

You can refer to valid dimensions and metrics in Google’s official documentation using the link API Dimensions & Metrics  |  Google Analytics  |  Google for Developers.

Step 6: Re-generate access token

Your access token will expire after one hour. You can’t fetch data again. It shows a client error. So after every hour, you have to regenerate an access token by using the refresh token. This refresh token logic will help to regain the new access token. But after some days, the refresh token also expires. But it has a longer life than an access token.

If the refresh token expires, it shows ‘Refresh Error’. Don’t worry, just authenticcate ur account again. Follow step 4.

curl -X POST https://oauth2.googleapis.com/token \
  -d client_id=YOUR_CLIENT_ID \
  -d client_secret=YOUR_CLIENT_SECRET \
  -d refresh_token=YOUR_REFRESH_TOKEN \
  -d grant_type=refresh_token
Enter fullscreen mode Exit fullscreen mode

Here, replace your client ID, client secret, and refresh token obtained before. You will get the same refresh token again and again until it expires. If you have any doubts, feel free to reach out to me in the comments 📌.

Top comments (0)