sayam
sayam

Reputation: 163

Accessing google analytics through nodejs

I'm using nodejs, and I would like to display some data from google analytics.

On google API explorer, I've find this url to get my data:

https://www.googleapis.com/analytics/v3/data/ga?ids=ga%XXXXX&start-date=2013-08-17&end-date=2013-09-15&metrics=ga%3Avisits&key={YOUR_API_KEY}

However, if I access this url I get:

{"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}}

How can I pass my login through the url and then access my data ?

Thanks!

Upvotes: 7

Views: 7541

Answers (4)

jignesh kumar
jignesh kumar

Reputation: 519

Below I have mentioned step by step process for Accessing google analytics through nodejs:

For more details : How To Use Google Analytics Reporting API With Nodejs

Install googleapis package

npm i googleapis

Import const { google } = require('googleapis')

This is sample scripts for getting total views in last month:

const { google } = require("googleapis");

const scopes = "https://www.googleapis.com/auth/analytics.readonly";

const jwt = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  process.env.PRIVATE_KEY.replace(/\\n/g, "\n"),
  scopes
);
const view_id = "Your_View_ID";

async function getViews(){
  try {
    await jwt.authorize();

    const response = await google.analytics("v3").data.ga.get({
      auth: jwt,
      ids: "ga:" + view_id,
      "start-date": "30daysAgo",
      "end-date": "today",
      metrics: "ga:pageviews",
    });

    console.log(response);

  } catch (err) {
     console.log(err);
  }
};`

Upvotes: 0

Abel Dias
Abel Dias

Reputation: 11

@xavier.seignard I follow your snippet but with modifications because I'm using a json file instead of p12 (code below). But I have a doubt, I'm developing a restful backend in nodejs. In this case, isn't it necessary to put the ga.get function inside the app.use() to obtain analytics information for every request that is made?

var key = require('filename.json');
var authClient = new JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/analytics.readonly']);

Upvotes: 0

xavier.seignard
xavier.seignard

Reputation: 11154

From the Google API console, you need to activate the Analytics API, and finally setup a Service Account, you'll then download a *.p12 file.

From this *.p12 file, you need to convert it to a *.pem file, to do that, run the following:

openssl pkcs12 -in XXXXX.p12 -nocerts -nodes -out XXXXX.pem

You'll be asked a password, it should be notasecret

Now you got the *.pem file you need, and the account email is the one displayed in the google api console, as EMAIL ADDRESS.

Don't forget to add this address to your analytics account (see: Analytics Google API Error 403: "User does not have any Google Analytics Account")

You should be good to go with the following snippet:

var googleapis = require('googleapis'),
    JWT = googleapis.auth.JWT,
    analytics = googleapis.analytics('v3');

var SERVICE_ACCOUNT_EMAIL = 'XXXXXXXXXX@developer.gserviceaccount.com';
var SERVICE_ACCOUNT_KEY_FILE = __dirname + '/key.pem';


var authClient = new JWT(
    SERVICE_ACCOUNT_EMAIL,
    SERVICE_ACCOUNT_KEY_FILE,
    null,
    ['https://www.googleapis.com/auth/analytics.readonly']
);

authClient.authorize(function(err, tokens) {
    if (err) {
        console.log(err);
        return;
    }

    analytics.data.ga.get({ 
        auth: authClient,
        'ids': 'ga:XXXXXXXX',
        'start-date': '2015-01-19',
        'end-date': '2015-01-19',
        'metrics': 'ga:visits'
    }, function(err, result) {
        console.log(err);
        console.log(result);
    });
});

Upvotes: 11

arami
arami

Reputation: 593

Are you setting Content-Type to application/x-www-form-urlencoded?

If you're still stuck, it's worth noting that Google has released a nodejs client library (alpha) here: https://github.com/google/google-api-nodejs-client

Upvotes: 0

Related Questions