# How to use Google Analytics Data API

In this article, I am going to walk you through that how you [Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) to fetch data from [Google Analytics](https://analytics.google.com/) 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](https://j471n.in/), I have just implemented [Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) 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](https://j471n.in/):

![](https://i.imgur.com/gFNCTvQ.png align="center")

## 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](https://analytics.google.com/).
    
* 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.

![](https://i.imgur.com/scjFbin.png align="center")

### `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](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries) and then click on **Enable the Google Analytics Data API v1** button as shown in the image below:

![](https://i.imgur.com/WrN2YwC.png align="center")

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

![](https://i.imgur.com/2BwwX84.png align="center")

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

![](https://i.imgur.com/TU6qYrV.png align="center")

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](https://www.npmjs.com/package/@google-analytics/data) package. You can do that by simply running the following command in the terminal.

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

## Using Google Analytics Data API in Project

As I am using [Next.js](https://nextjs.org/) for my portfolio so I will use [Next.js API Routes](https://nextjs.org/docs/api-routes/introduction). You can do the same thing with different frameworks.

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

```typescript
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", // I wanted the data be year wised
      },
    ],
    metrics: [
      {
        name: "activeUsers", // it returs the active users
      },
    ],
  });

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

This is all you need to fetch the data. and It will return the response. My portfolio code can be found on [GitHub](https://github.com/j471n/j471n.in/blob/main/pages/api/ga.ts) you can check out How I used it.

You can play with [Dimensions and Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema) 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 |
| --- | --- | --- | --- | --- | --- | --- |
|  |  |  |  |  |  | \[\] |
