Google has lots of good documentation on starting out with Google APIs (which is used for Google Analytics) for certain languages like Python, Java, and C#, but completely sketchy for Node.js. Googling there are many examples but most are for v3. And the implementations get confusing if you aren’t familiar with oAuth or JSON Web Tokens.

Here is a really simplified chunk of starter code for pulling the number of Goal 2 completions by source/medium, ordered in descending order. The assumption is that you have already set up the service account and downloaded the JSON file with the private key.

var prettyjson = require('prettyjson'); // Un-uglify JSON output
var {google} = require('googleapis');
var key = require('<SERVICE_ACCOUNT_JSON_FILE>'); // Downloaded JSON file

var viewID = '<VIEW_ID>'; // Google Analytics view ID
var analytics = google.analyticsreporting('v4'); // Used for pulling report
var jwtClient = new google.auth.JWT(key.client_email, // For authenticating and permissions
                                    null,
                                    key.private_key,
                                    ['https://www.googleapis.com/auth/analytics.readonly'],
                                    null);

jwtClient.authorize(function (err, tokens) {
  if (err) {
    console.log('Reeeeejected');
    console.log(err);
    return;
  } else {
    console.log('Yup, we got authorized!');
  }
});

// Set up what we data we want to pull from Google Analytics
metrics_columns = [{
  expression: 'ga:goal2Completions'
}];

dimensions_rows = [{
  name: 'ga:sourceMedium'
}];

date_filters = [{
  startDate: 'today',
  endDate: 'today',
}];

sort = [{
  fieldName: 'ga:goal2Completions',
  sortOrder: "DESCENDING"
}];

var req = {
  reportRequests: [{
    viewId: viewID,
    dateRanges: date_filters,
    metrics: metrics_columns,
    dimensions: dimensions_rows,
    orderBys: sort
  }],
};

// Options for prettifying JSON output
var pretty_json_options = {
  noColor: false
};

// Pull report and output the data
analytics.reports.batchGet({
    auth: jwtClient,
    resource: req
  },
  function (err, response) {
    if (err) {
      console.log('Failed to get Report');
      console.log(err);
      return;
    }
    // response.data is where the good stuff is located
    console.log('Success - got something back from the Googlez');
    console.log(prettyjson.render(response.data, pretty_json_options));
  }
);

Make Haste Slowly

Are you tired of all the bullshit business, marketing and technology news out there? Do you have a bad case of FOMO? The signal to noise ratio is entirely out of whack nowadays. All the incentives are misaligned. If you want an unbiased view on on the intersection of technology, marketing, products/services and the impacts on consumers, businesses, and society in general, sign up below.

You have Successfully Subscribed!