1

first question so bear with me.

I am using NodeJS to query the Google Analytics Reporting API. I am able to receive the OAuth 2 token I need, and when I query the API I get a 200 response back. However the payload that returns is an empty object instead of the JSON formatted report response that is the intended goal.

var https = require('https');
var google = require('googleapis');
var key = require('path/to/key');
var jwtClient = new google.auth.JWT(key.client_email,null,key.private_key,'https://www.googleapis.com/auth/analytics.readonly',null);

var getGoogleData = google.analyticsreporting('v4');

var googleTemplates = {"reportRequests":[{"viewId": "######","dateRanges": [{"startDate": "2014-11-01", "endDate": "2014-11-30"}],"metrics": [{"expression": "ga:users"},{"expression": "ga:newUsers"},{"expression": "ga:pageviews / ga:sessions"}]},{"viewId": "######","dateRanges": [{"startDate": "2014-11-01", "endDate": "2014-11-30"}],"metrics": [{"expression": "ga:transactionRevenue"},{"expression": "ga:transactions"},{"expression":"ga:transactions / ga:sessions"},{"expression":"ga:revenuePerTransaction"}]}]};
var googleToken={};


var requestReport = function(reportRequest,token){


    reportRequest = JSON.stringify(reportRequest);
    //console.log(reportRequest);

    var requestObject = {
        method:'POST',
        hostname:'analyticsreporting.googleapis.com',
        path:'/v4/reports:batchGet',
        headers:{
            Accept:'*/*',
            Authorization:'Bearer '+token.access_token,
            'Content-Type':'application/x-www-form-urlencoded'
        }
    };

    var callbackGoogle = function(response){
        console.log('\n-----------------------\n');
        console.log('Requesting Report : Google Analytics\nStatus Code: [', response.statusCode +': '+ response.statusMessage+']');
        console.log('-----------------------\n\n');

        var data = [];

        response.on('data',function(chunk){
            data.push(chunk);
        });
        response.on('end',function(){
            var buff = new Buffer(data.join('')).toString();

            console.log('////////////////////////// Success //////////////////////////\n')
            console.log(buff);

        });

        response.on('error',function(e){
            console.log(e);
        });
    };

    var req = https.request(requestObject,callbackGoogle);
    req.on('error',function(e){
            console.log('requestReport Error:\n',e);
        });
    req.write(reportRequest);
    req.end();

};

(function googleAccess(){
    jwtClient.authorize(function(err,tokens){
        console.log('\n-----------------------\n');
        console.log('Authenticate: Google \n');

        if(err){
            console.log('Google Error',err);
            return;
        }

        googleToken = tokens;

        requestReport(googleTemplates,tokens);

        console.log('Success: true');
        console.log('\n-----------------------\n\n');
    })
})();

The console output is as follows:

-----------------------

Authenticate: Google 

Success: true

-----------------------

-----------------------

Requesting Report : Google Analytics
Status Code: [ 200: OK]
-----------------------

////////////////////////// Success //////////////////////////

{}

Does anyone have a suggestion as to why the payload is returning as an empty object? It should be a report JSON file.

4
  • You should try just console.log(response); to see the entire output. It appears you've installed the google apis and even have the analyticsreporting service object (getGoogleData in your code) but you are not using it; is there a reason? Commented Jun 17, 2016 at 20:24
  • I did actually try that. I can post the whole response object Monday. The reason I am not using the analyticsreporting service object is that the documentation on it was sparse, and I was somewhat confused as to what the attached method getGoogleData.reports.batchGet() was expecting to have passed into it. I decided to try the process manually, but only after I tried the method batchGet first. When I do use the methods attached to the service I receive a 'NULL' response, and Google logs 401 and 403 errors or nothing. Information on the batchGet method would be welcome! Thanks! Commented Jun 18, 2016 at 23:16
  • More examples: The samples page are written with the default javascript library. are written in the serviceobject.method(requestbody).execute(callbackmethod) format, the quickstart guide is written with promoses, aslo using the service object. Commented Jun 20, 2016 at 14:41
  • If the default method is returning 403 or 401 it could either be because Auth is set up incorrectly or that you are using the wrong viewID. These are just the two most popular errors but it is equally possible that your there is something wrong with your requests. from your template above you are attempting to make two requests in one batch get. I'd first debug getting a single request working and then add extra reportRequest objects. Commented Jun 20, 2016 at 14:44

1 Answer 1

0

I found the issue! File this one under 'not seeing the forest for the trees'.

The requestObject should have 'Content-type':'application/json'.

Sign up to request clarification or add additional context in comments.

2 Comments

Any reason why you are not using the node js sdk from google?
This task involved integrating data from Google Analytics and Adobe Analytics. Ultimately I did use a library from Google, but I as I recall I had to do some data packaging gymnastics to get the project dashboard to display both data sources together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.