Skip to content

Instantly share code, notes, and snippets.

@joost
Last active November 27, 2023 15:43
Show Gist options
  • Save joost/5344705 to your computer and use it in GitHub Desktop.
Save joost/5344705 to your computer and use it in GitHub Desktop.
Google Analytics API (server-to-server) using Ruby

There are many (old) clients available:

The Google Analytics API is at v3 (at time of writing).

This example uses Google's Ruby API client to access Analytics. Use https://github.com/google/google-api-ruby-client (Google supported).

For server-to-server Analytics API:

Now get access to the Analytics API in your Ruby/Rails app:

  require 'google/api_client'
  require 'date'

  client = Google::APIClient.new(:application_name => 'something you like', :application_version => '1')
  key_file = File.join('SOME PATH', 'KEY_FILE')
  key = Google::APIClient::PKCS12.load_key(key_file, 'notasecret')
  service_account = Google::APIClient::JWTAsserter.new(
      SERVICE_ACCOUNT_EMAIL,
      ['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/prediction'],
      key)
  client.authorization = service_account.authorize

  analytics = client.discovered_api('analytics', 'v3')

  result = client.execute(:api_method => analytics.management.accounts.list)
  result.data.items.first.id

  parameters = {
        'ids'         => "ga:SOME_ID",
        'start-date'  => (Date.today - 30).strftime("%Y-%m-%d"),
        'end-date'    => Time.now.strftime("%Y-%m-%d"),
        'metrics'     => "ga:avgTimeOnPage",
        'filters'     => "ga:pagePath=~/"
      }
  result = client.execute(:api_method => analytics.data.ga.get, :parameters => parameters)
@santucorephp
Copy link

Just found it. Turns out it was deprecated . So now you need the googleauth gem, which is installed along with the API client. Basically you just need to require the class for the API you want to query. Brief example:

> require 'google/apis/analyticsreporting_v4'
> analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
> credentials = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: IO.new(IO.sysopen('credentials.json')))
> credentials.scope = 'https://www.googleapis.com/auth/analytics.readonly'
> analytics.authorization = credentials.fetch_access_token!({})["access_token"]
> 
> request = {report_requests:[
>         {metric:[{expession: "ga:users"}],
>          dimensions:[{name:"ga:pagePath"}],
>          date_ranges:[{start_date: "2016-12-28", end_date: "2017-01-26"}],
>          view_id:"ga:88064121",
>          filters_expression: "ga:pagePath=@solicitudes"
> }]}
> 
> results = analytics.batch_get_reports Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(request)
> ```

I have tried this but same error will appear "User does not have sufficient permissions for this profile".

namespace :analyze do
  desc 'Google Analytics has been started'
  task query_for_google_analytics_data_api_v4: :environment do
    require 'google/apis/analyticsreporting_v4'
    set_start_date = "2022-08-08"
    set_end_date = "2022-09-09"
    analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
    credentials = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open('sales-322705-f48f750568d2.json'),
      scope: 'https://www.googleapis.com/auth/analytics.readonly'
    )
    analytics.authorization = credentials.fetch_access_token!({})["access_token"]
    p analytics.authorization
    date_range = Google::Apis::AnalyticsreportingV4::DateRange.new(start_date: set_start_date, end_date: set_end_date)

    metric = Google::Apis::AnalyticsreportingV4::Metric.new(expression: 'ga:sessions', alias: 'sessions')
    dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:browser')

    request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
      report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
        view_id: '331568465',
        metrics: [metric],
        dimensions: [dimension],
        date_ranges: [date_range]
      )]
    )

    response = analytics.batch_get_reports(request)
    response.reports
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment