0% found this document useful (0 votes)
94 views

CALL GOOGLE ANALYTICS API USING NODEJS - v1.0

The document provides steps to call the Google Analytics API using Node.js. It includes: 1) Creating a Google API project and enabling the Google Analytics API. 2) Generating authentication credentials in JSON format. 3) Adding the service account to a Google Analytics view and getting the view ID. 4) Writing Node.js code to call the API using the credentials and view ID.

Uploaded by

tuanv2t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

CALL GOOGLE ANALYTICS API USING NODEJS - v1.0

The document provides steps to call the Google Analytics API using Node.js. It includes: 1) Creating a Google API project and enabling the Google Analytics API. 2) Generating authentication credentials in JSON format. 3) Adding the service account to a Google Analytics view and getting the view ID. 4) Writing Node.js code to call the API using the credentials and view ID.

Uploaded by

tuanv2t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

CALL GOOGLE ANALYTICS API USING NODEJS

Author: [email protected]

QAK Solutions ( qaksolutions.com )

Version :1.0

Date: Dec 13, 2019

Assume you have already had a google Analytics account

Overview:

Step 1: Create google Api project and enable Google Analytics API

Step 2: Create Authentication Credentials to be used in nodejs

Step 3: Add user in step 2 in google analytics account and get view Id

Step 4: Write nodejs code and run

Detail:

Step 1: Create google Api project and enable Google Analytics API

Go to http://console.developers.google.com/

If you already have a project, then you can use your existing project
In my example, I already have existing project "demo1"/

You can create a new project by clicking on NEW PROJECT

Open Dashboard or your project, click on ENABLE APIS AND SERVICES

Type google analytics

Click on Google Analytics API and Enable it

Step 2: Create Authentication Credentials to be used in nodejs

Back to https://console.developers.google.com/
Your screen will different from mine, because I have some testing credentials
before

> Click on Create credentials

Select "Service account key"


Type your prefer name of the service account name, such as in my example

Note: Should check option "JSON"

Click on Role to select a Role


You can select any role according to your business, in this example , I select
Monitoring Admin

Then click on Create button

If there is no error, a json file will be downloaded to your computer, the


content of the json looks like this

You can rename the json file to another beautiful name, such as
google_auth.json

This file will be used in your nodejs code in step 4


Now go to step 3

Step 3: Add user in step 2 in google analytics account and get view Id

You must have already a website , go to your Analytics account at google


Analytics

As my example

Click on Admin
Click on User Management

You might see your email is already existing here

Click on + button on the top right

Click on Add users


Now open the json file to find the client_email

Copy the client_email and paste to the Email to create

Just allow Read & Analyse only

Click on Add => Done


Now getting the view id

Go back to your analytics admin, click on View Settings

Step 4: Write nodejs code and run

After getting view id, now it's ok to use view id in your code

Download my example code at https://github.com/tuanv2t/Google-Analytics-


API-Nodejs
Replace content in google_auth.json with your information

Or simple overwrite my file with your google_auth.json at step 2

Open auth_demo.js and replace your view id

Now run npm install

And then node auth_demo.js

In my case :
The result will looks like this

Some examples calling google analytics api :


'use strict'
const { google } = require('googleapis')
const key = require('./google_auth.json')
const scopes = 'https://www.googleapis.com/auth/analytics.readonly'
const jwt = new google.auth.JWT(key.client_email, null, key.private_key, scopes)
const view_id = '20xxx500'
process.env.GOOGLE_APPLICATION_CREDENTIALS = './google_auth.json'
const defaultCredential = {
'auth': jwt,
'ids': 'ga:' + view_id,
}
async function main() {

/*Get the number of today sessions*/


const sessionTodayData = await google.analytics('v3').data.ga.get({
...defaultCredential,
'start-date': 'today',
'end-date': 'today',
'metrics': 'ga:sessions'
});
console.log(sessionTodayData);
/* Get the number of today sessions coming from organic sources (Search Engines)
*/
const todaySessionsComingFromOrganicData = await
google.analytics('v3').data.ga.get({
...defaultCredential,
'start-date': 'today',
'end-date': 'today',
'metrics': 'ga:sessions',
'filters': 'ga:medium==organic',
});
console.log(todaySessionsComingFromOrganicData);
console.dir(todaySessionsComingFromOrganicData.data.rows[0][0])
/* Get the number of sessions in the last 30 days */
const sessionLast30Data = await google.analytics('v3').data.ga.get({
...defaultCredential,
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions'
});
console.log(sessionLast30Data);
console.dir(sessionLast30Data.data.rows[0][0])
/* Get the browsers used in the last 30 days */
const browserLast30Data = await google.analytics('v3').data.ga.get({
...defaultCredential,
'start-date': '30daysAgo',
'end-date': 'today',
'dimensions': 'ga:browser',
'metrics': 'ga:sessions'
});
console.log(browserLast30Data);
console.dir(browserLast30Data.data.rows.sort((a, b) => b[1] - a[1]))
/* Get the number of visitors using Chrome */
const chromeLast30Data = await google.analytics('v3').data.ga.get({
...defaultCredential,
'start-date': '30daysAgo',
'end-date': 'today',
'dimensions': 'ga:browser',
'metrics': 'ga:sessions',
'filters': 'ga:browser==Chrome',
});
console.log(chromeLast30Data);
console.dir(browserLast30Data.data.rows.sort((a, b) => b[1] - a[1]))
/* Get the sessions by traffic source */
const trafficSourceLast30Data = await google.analytics('v3').data.ga.get({
...defaultCredential,
'start-date': '30daysAgo',
'end-date': 'today',
'dimensions': 'ga:source',
'metrics': 'ga:sessions'
})
console.dir(trafficSourceLast30Data.data.rows.sort((a, b) => b[1] - a[1]))
}
main()

Source code in git: https://github.com/tuanv2t/Google-Analytics-API-


Nodejs/blob/master/index.js

just type: node index

You might also like