Sunday, May 19, 2024
HomeTechnologyGoogle Analytics Core Reporting API v4 with Ruby sample code!

Google Analytics Core Reporting API v4 with Ruby sample code!

Google Analytics Core Reporting API V4 was suddenly released in April 2016, but I tried using the API to the fullest, so if you are interested, please use the sample program and give it a try.

thumbnail 12

Overview of version 4

In version 4,

  • It is now possible to specify multiple periods instead of a single period.
  • Multiple segments can now be specified and output at once
  • You can now specify metrics with custom formulas on the fly
  • Added cohort-related dimension metrics
    • It is now possible to obtain referrers/media and campaigns at the time of initial inflow for each user (unconfirmed)
    • Added lifetime value metrics
  • Multiple reports can now be retrieved with a single API request
  • By specifying the conditions for the pivot table, the API response format will be pivoted
  • Dimensions that have numerical values ​​assigned to them, such as the dimension Sessions, will allow you to specify the interval width (histogram buckets) for the dimension. Fixed values ​​such as 1, 2, 3, 4, 5, 6, 7, 8, 9-14, 15-25, 26-50 can now be dynamically specified. Become.

It is powered up in such a form. Perhaps because the condition specification related to report generation has become complicated, API requests are now in the format of setting parameters in JSON format in the request body with POST requests instead of GET requests so far.

It seems that other authentication-related and dimensional metrics that were basically available until now can still be used.

Please note that to use version 4 API, you need to enable Analytics Reporting API V4 from Google Developer Console .

Client library support status

It seems that client libraries for most languages ​​do not support it yet. There is barely any Python code in Migrations , and a link to a Github project called gav4-python , so if you want to do whatever it takes right now, Python is a good choice. That said, the code in the gav4-python project doesn’t seem to be official, and you can make API calls just by making raw HTTP requests, so you don’t have to stick to Python.

In fact, I’m more of a Ruby person than Python, so I wrote a simple program to run the Core Reporting API V4 using raw HTTP requests in Ruby.

Preparing for execution in Ruby

Step 1: Enable the API from the Developer Console

To use version 4 of the API, enable Analytics Reporting API V4 from the Google Developer Console . Even if you are already using the Google Analytics Core Reporting API, you need to enable the API in V4 alone.

Even if you forget to enable it, you’ll quickly notice it as you’ll get a polite error message when you run the API.

Step 2: Get an AccessToken

If you’re already using the API, I don’t think it’s a big deal. Authenticate with OAuth2.0 and get an AccessToken. If there is RefreshToken, get AccessToken from RefreshToken.

Step 3: Implement a Convenience Class for API Execution

require 'net/https'
require 'uri'
class CoreReportingV4Client
  def initialize(access_token)
    @access_token = access_token
  end

  def query(params)
    uri = URI.parse('https://analyticsreporting.googleapis.com/v4/reports:batchGet')
    request = Net::HTTP::Post.new(uri.path, {
      'Content-Type' => 'application/json',
      'Authorization' => "Bearer #{@access_token}",
    })
    request.body = params.to_json
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    response = http.start { |h| h.request(request) }
    JSON.parse(response.body)
  end
end

I think that many people assume a long program, but if you write it in Ruby, you can implement the basic part in only about 20 lines. At first, when I ran it without specifying “Content-Type”, the response body was only “{}” and it was trial and error, but if I specified “Content-Type”, the data was returned without any problems. I will come.

Step 4: Run the API to Get the Report

client = CoreReportingV4Client.new('ここにアクセストークンを指定する')
puts client.query({
  reportRequests: [{
    viewId: "95664386",
    dateRanges: [{
      startDate: "2016-01-01",
      endDate: "2016-01-31",
    }],
    metrics: [{ expression: "ga:sessions" }],
    dimensions: [{ name: "ga:medium" }],
  }]
})

If you simply want to output the number of sessions by media, you can implement it as above. When you try to output pivot tables, cohorts, etc., the condition specification becomes more and more complicated.

Impressions after using it and for the future

In fact, most of the report functions newly implemented in V4 were realized by combining programming languages ​​such as Ruby and JavaScript. Although it became possible to specify multiple periods in V4, even in V3 you could do the same thing by calling the API multiple times with different periods. The same applies to specifying multiple segments and batch acquisition of multiple reports. Also, formula calculations and pivot tables can be implemented in the same way on the program side, and cohorts can be achieved by calling the API many times. However, parts that have been implemented on the program side, such as Ruby and JavaScript, can now be directly specified as API arguments, so it is believed that the readability of the program will be greatly improved.

In addition, the addition of cohort-based dimensions and lifetime value-based metrics has expanded the scope of what can be done. Although it has not been verified yet, it should be possible to output the lifetime value of each media.

I will continue to use V4’s Reporting API and share any interesting discoveries.

RELATED ARTICLES

Leave a reply

Please enter your comment!
Please enter your name here

Recent Posts

Most Popular

Recent Comments