Skip to content
weenhanceitPublic

About

A Ruby library and command-line interface to Google Analytics Reporting v4

Resources

Stars

1 star

Watchers

2 watching

Forks

Latest commit

 

History

77 Commits

Folders and files

Repository files navigation

Google Analytics Reporting for Ruby

gaapi provides:

  • A command line executable program to retrieve reporting data from Google Analytics (GA). It takes the user's GA request, specified in JSON format, and sends it to GA. It outputs the result of the request in JSON or comma-separated values (CSV) format
  • A library of classes that can be used in other programs to retrieve reporting data from GA

gaapi supports two ways of providing credentials. One way is more useful while testing scripts or doing ad-hoc queries. The other is more appropriate for unattended script usage. See the Authentication section for more details.

Google provides a Ruby client library that builds queries by constructing them from Ruby objects. gaapi allows you to express queries as JSON. If you prefer the JSON format, you may prefer to use gaapi. If you want to deal with Ruby objects (which are likely more verbose than JSON), use the Google gem.

Installation

For stand-alone use:

gem install gaapi --no-doc

In a Gemfile:

gem 'gaapi'

Usage

Command Line

gaapi [options] VIEW_ID

If no query is specified on the command line, gaapi tries to read the query from standard input.

The VIEW_ID is what identifies the GA data (a view of a property). To find the view ID, log in to GA, select the account of interest, select Admin (the gear near the bottom left of the page), and select "View Settings" (on the right of the page).

Options

    -a, --access-token TOKEN         An access token obtained from https://developers.google.com/oauthplayground.
        --csv                        Output result as a csv file.
    -c, --credentials CREDENTIALS    Location of the credentials file. Default: `.gaapi/ga-api-key`.
    -d, --debug                      Print debugging information.
    -e, --end-date END_DATE          Report including END_DATE (yyyy-mm-dd).
    -n, --dry-run                    Don't actually send the query to Google.
    -q, --query-file QUERYFILE       File containing the query. Default STDIN.
    -s, --start-date START_DATE      Report including START_DATE (yyyy-mm-dd).

If you specify both the -a and -c options, gaapi will use the -a option.

Example

Get the number of visitors to a site for January, 2018, with credentials previously obtained and stored in ./credentials.json:

gaapi -s "2018-01-01" -e "2018-01-31" -c ./credentials.json 000000
{
  "reportRequests": [{
      "viewId": "VIEW_ID",
      "dimensions": [{"name": "ga:date"}],
      "dateRanges": [{
        "startDate": "START_DATE",
        "endDate": "END_DATE"
      }],
      "metrics": [{
          "expression": "ga:users"
      }],
      "includeEmptyRows": true,
      "hideTotals": false,
      "hideValueRanges": true
    }]
}

In a Program

Make sure the program can find GAAPI. Without Rails:

require "gaapi"

With Rails, simply include gaapi in the Gemfile:

gem "gaapi"

Next, get an access token. To run the program unattended, the best way is to use the approach described [here](#Unattended Running), which translates to the following code:

access_token = GAAPI::AccessToken.new("path/to/credential_file")

Set up the query. This may raise exceptions:

begin
  query = GAAPI::Query.new(query_string, 00000000, access_token, "2018-01-01", "2018-06-30")
rescue StandardError => e
  # Handle the error
end

A typical exception would be from a query_string that isn't valid JSON. The query_string has to be a valid GA reporting query. See the Queries section. Because the access token is lazy-evaluated, you may also get an exception here if the credential file doesn't exist or is malformed.

Execute the request:

result = query.execute
if result.success?
  ...
end

If the query was successful, you have access to a few interesting methods:

puts result.body  # raw response body
puts result.pp    # a string formatted into more readable JSON
puts result.csv   # comma-separated values format, ready to be written to a file

There is also some support now for a more structured use of the resulting query. If the query was successful (result.success?), you can use the following:

result.reports    # An array of GAAPI::Report objects
report.dimensions # An array of the dimension names
report.headers    # An array of the dimension names and metric names
report.metrics    # An array of the metric names
report.rows       # An array of GAAPI::Row objects

If you have a Row object, you can access the dimensions and metrics using method names. For example, to get the ga:sessionDuration metric for a row:

row.session_duration

The ga: is stripped from the front of the dimension or metric name, and then the rest is converted to snake case.

You can also get all the dimensions or all the metrics for a row:

row.dimensions
row.metrics

These return arrays with the values in the order corresponding to the