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!
4 Answers 4
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 = '[email protected]';
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);
});
});
Comments
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
1 Comment
@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']);
Comments
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);
}
};`
Comments
Explore related questions
See similar questions with these tags.
&key={YOUR_API_KEY}https://www.googleapis.com/analytics/v3/data/ga?ids=ga:XXXXX88&metrics=ga:visits&start-date=2013年08月17日&end-date=2013年09月15日&access_token=XXXXXXXX&access_type_token=bearerand everything works.https://accounts.google.com/o/oauth2/token?client_secret=XXX&grant_type=refresh_token&refresh_token=YYYY&client_id=ZZZZI geterror, invalid request.