Google Analytics API: Get Sessions per hour

1.5k views Asked by At

I need to create some database entries from our Google Analytics API. Very important to note is that I'm only requesting this data once at midnight every day. Here are the details:

Data Needed: Object:

{ sessions: Int, hourOfDay: Int date: 'YYYY-MM-DD }

I need that data for every hour of the day. I would like to get that either as actual values for a period of 7 days (aka, 24 objects repeating for 7 days), or the avg value of the past week for that hour (aka, 24 objects with the avg value of the past 7 days at that hour.)

Here's some example code, which I know will need to be edited for this purpose:

authorize(function(err, token) {
  const weekInSeconds = 436800000;
  const endDate = new Date();
  const startDate = new Date(endDate.getTime() - weekInSeconds);

  // Code to convert startDate + endDate to Strings (e.g: '2017-01-05')

  var requestConfig = {
    'ids': 'ga:1234567890',
    'start-date': endDateStr,
    'end-date' : startDateStr,
    'metrics': 'ga:sessions'
  };

  // Code here sends request to Google API

});

requestConfig is the key here, or potentially the start/ed dates are. Here's the knowledge I lack right now:

Is it possible to use the 'metrics' field in requestConfig to order to get the date object described above?

My other train of thought is to make batches of requests in parallel for each different field, and create objects from the aggregated responses. Explanation of this(psuedo-code):

for (each hour of past 7 days) {
  var requestConfig = {
      'ids': 'ga:1234567890',
      'start-date': endDateStr,
      'end-date' : startDateStr,
      'metrics': 'ga:sessions'
  };

  // Create fields for hour, date | fill with appropriate value
  // Send requestConfig and create field in object from response
}

I'd prefer to just get the former approach, since it requires less fiddling with the API and fewer places to introduce bugs.

2

There are 2 answers

2
William Carron On

Never mind, I have found the answer. I learned that there exists another field: 'dimensions', in the API object, by which I can group the results by various parameters (e.g hour, minute, date, dateHour, etc).

0
Elvira On

I've found the query explorer really helpful and useful see query explorer