Search code examples
google-analyticsanalyticsgoogle-analytics-apiuniversal-analytics

Google Analytics V4 API: Get data for last 30 days


I'm playing around with the reporting api v4 from google analytics. I want to display a graph in my backend, where I show the last 30 days of some metrics. The problem is, I only get accumulated / summed values.

For example this is a body I'm sending to the api

  body = {
    reportRequests: [{
      dateRanges: [
        {
          startDate: Date.parse('2016/10/01'),
          endDate: Date.parse('2016/10/31')
        }
      ],
      viewId: '12345',
      metrics: [{ expression: "ga:users" }],
      dimensions: [{ name: "ga:pagePath" }]
    }]
  }

And then I get a lot of URLs (of course, I haven't filtered the output) like this:

{"reports"=>
  [{"columnHeader"=>
     {"dimensions"=>["ga:pagePath"],
      "metricHeader"=>
       {"metricHeaderEntries"=>[{"name"=>"ga:users", "type"=>"INTEGER"}]}},
    "data"=>
     {"rows"=>
       [{"dimensions"=>["/"], "metrics"=>[{"values"=>["2854"]}]},
        {"dimensions"=>["/?extlink_img=0"], "metrics"=>[{"values"=>["113"]}]},
        {"dimensions"=>["/?v=338"], "metrics"=>[{"values"=>["12"]}]},
        ...

But how should I query the api, when I want the user count of the last 30 days, for a specific route, e.g. /? Is this even possible?


Solution

  • I found it out by myself, there is a dimension for this: ga:date:

      body = {
        reportRequests: [{
          dateRanges: [
            {
              startDate: Date.parse('2016/10/01'),
              endDate: Date.parse('2016/10/31')
            }
          ],
          viewId: '12345',
          metrics: [{ expression: "ga:users" }],
          dimensions: [{ name: "ga:pagePath" }, {name: 'ga:date'}]
        }]
      }
    

    There are other time related dimensions as well https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=time