DEV Community

Cover image for How to use Google Analytics Data API
Jatin Sharma
Jatin Sharma

Posted on • Updated on • Originally published at j471n.in

How to use Google Analytics Data API

In this article, I am going to walk you through that how you Google Analytics Data API to fetch data from Google Analytics in the simplest way I can. After reading this article you'll be able to use this in your project with ease. So without further due, Let's jump into it.

In my portfolio, I have just implemented Google Analytics Data API so that I can show how many people have visited this site in the last 7 days. As my Portfolio is already using Google Analytics to track user visits. I just need to use its API to fetch that data.

But first, look at how it's showing in my portfolio:

Requirements

We need three values to fetch the data:

  • GA_PROPERTY_ID
  • GA_CLIENT_EMAIL
  • GA_PRIVATE_KEY

GA_PROPERTY_ID

First, you need to get GA_PROPERTY_ID of the Google Analytics project from which you want to fetch the data.

To get this you need to follow these steps:

  • Visit Google Analytics.
  • Select Admin.
  • Select the Property.
  • Select Property Settings.

If the Property Settings shows a numeric PROPERTY ID such as "123...", this is the numeric Id of your Google Analytics 4 property.

GA_CLIENT_EMAIL and GA_PRIVATE_KEY

To get GA_CLIENT_EMAIL and GA_PRIVATE_KEY you need to visit Google Analytics Data API's documentation and then click on Enable the Google Analytics Data API v1 button as shown in the image below:

And then you will be prompted to enter the name of the project. After entering the name click on the Next button

Then you will be prompted to download the credential file as JSON.

After downloading that file. You will find private_key and client_email properties in that JSON file. Save these two in your .env.local.

Now you have all the necessary information or keys.

Installing Dependency

To fetch the data you need to install a @google-analytics/data package. You can do that by simply running the following command in the terminal.



yarn add @google-analytics/data
# or 
npm i @google-analytics/data
# or
pnpm i @google-analytics/data


Enter fullscreen mode Exit fullscreen mode

Using Google Analytics Data API in Project

As I am using Next.js for my portfolio so I will use Next.js API Routes. You can do the same thing with different frameworks.

I will create an API route pages/api/ga.ts:



import { NextApiRequest, NextApiResponse } from "next";
import { BetaAnalyticsDataClient } from "@google-analytics/data";

// ๐Ÿ‘‡ Setting PropertyId
const propertyId = process.env.GA_PROPERTY_ID;

const analyticsDataClient = new BetaAnalyticsDataClient({
  credentials: {
    client_email: process.env.GA_CLIENT_EMAIL,
    private_key: process.env.GA_PRIVATE_KEY?.replace(/\n/gm, "\n"), // replacing is necessary
  },
});

export default async function handler(
  _req: NextApiRequest,
  res: NextApiResponse
) {
  // ๐Ÿ‘‡ Running a simple report
  const [response] = await analyticsDataClient.runReport({
    property: `properties/${propertyId}`,
    dateRanges: [
      {
        startDate: `7daysAgo`, //๐Ÿ‘ˆ  e.g. "7daysAgo" or "30daysAgo"
        endDate: "today",
      },
    ],
    dimensions: [
      {
        name: "year", // data will be year wise
      },
    ],
    metrics: [
      {
        name: "activeUsers", // it returs the active users
      },
    ],
  });

  // Returning the respose.
  return res.status(200).json({
    response,
  });
}


Enter fullscreen mode Exit fullscreen mode

The response would be:



{
  "data": {
    "dimensionHeaders": [
      {
        "name": "year"
      }
    ],
    "metricHeaders": [
      {
        "name": "activeUsers",
        "type": "TYPE_INTEGER"
      }
    ],
    "rows": [
      {
        "dimensionValues": [
          {
            "value": "2023",
            "oneValue": "value"
          }
        ],
        "metricValues": [
          {
            "value": "357",
            "oneValue": "value"
          }
        ]
      }
    ],
    "totals": [

    ],
    "maximums": [

    ],
    "minimums": [

    ],
    "rowCount": 1,
    "metadata": {
      "dataLossFromOtherRow": false,
      "currencyCode": "USD",
      "_currencyCode": "currencyCode",
      "timeZone": "America/Los_Angeles",
      "_timeZone": "timeZone"
    },
    "propertyQuota": null,
    "kind": "analyticsData#runReport"
  }
}


Enter fullscreen mode Exit fullscreen mode

This is all you need to fetch the data. and It will return the response. My portfolio code can be found on GitHub you can check out How I used it.

You can play with Dimensions and Metrics to get your desired data.

Wrapping up

In this article, I have explained how you can use the Google Analytics Data API to fetch data from Google Analytics. After reading this article, you should now be able to easily implement this API on your projects.

If you enjoyed this article, then don't forget to give โค๏ธ and Bookmark ๐Ÿท๏ธfor later use and if you have any questions or feedback then don't hesitate to drop them in the comments below. I'll see in the next one.

Connect with me

Twitter GitHub LinkedIn Instagram Website Newsletter Support

Top comments (8)

Collapse
 
arafat4693 profile image
Arafat

hello, if my rows array is empty, does that mean I have some errors or simply means I don't have any visitors yet?

Collapse
 
j471n profile image
Jatin Sharma

Hello Arafat,

If you are getting empty rows array or rowCount is 0, this simply means that the Google Analytics doesn't have any data of the requested metrics (in this case activeUsers). In other words you don't have any visitors.

P.S. In my blog, I have added a snippet of what the response would look like if you have visitors.

Collapse
 
kumarkalyan profile image
Kumar Kalyan

nice article @j471n

Collapse
 
j471n profile image
Jatin Sharma

Thanks mate โ˜บ๏ธ

Collapse
 
jon_snow789 profile image
Jon Snow

I was unaware that Google also provides Analytics APIs. ๐Ÿค”๐Ÿค”

Thank you for sharing .... Sharma ji ๐Ÿ˜Ž๐Ÿ˜Ž

Collapse
 
j471n profile image
Jatin Sharma

I guess Google provides API for it's every product (not sure though).

Collapse
 
neospy profile image
NeoSpy • Edited

The Google Analytics Data API is incredibly versatile for extracting valuable insights from your data. Start by setting up a project in the Google Cloud Console and enabling the API. Authentication is crucial, usually via OAuth 2.0. For querying data, familiarize yourself with the API's report types and dimensions/metrics selection to tailor your data analysis effectively. I stumbled upon AppMetrica. Its user-friendly dashboard was a beacon of simplicity in the complex sea of analytics. The no-code integration was a sigh of relief, slashing the steep learning curve and saving me countless hours.

AppMetrica's flexibility in data handling was a game-changer. I could tweak and tailor the analytics to fit my unique needs without wrestling with rigid structures. This adaptability proved invaluable when dissecting revenue streams from in-app purchases. The data painted a clear picture of where our earnings were blossoming and provided the insight needed to refine our monetization strategy.

Collapse
 
rodrisanchez1 profile image
Rodri Sanchez

Good post! You forget to explain that after create the credentials needs to be added on analytics account acces!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.