Search code examples
rubygoogle-analyticsgoogle-apigoogle-analytics-apigoogle-api-ruby-client

Google Analytics Reporting v4 with streams instead of views


I've just created a new Google Analytics property and it now defaults to data streams instead of views.

I had some code that was fetching reports through the API that I now need to updated to work with those data streams instead of views since there are not views anymore.

I've looked in the docs but i don't see anything related to data streams, anybody knows how this is done now?

Here's my current code that works with a view ID (I'm using the ruby google-api-client gem):

    VIEW_ID = "XXXXXX"
    SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'

    client = AnalyticsReportingService.new

    #server to server auth mechanism using a service account
    @creds = ServiceAccountCredentials.make_creds({:json_key_io => File.open('account.json'), :scope => SCOPE})
    @creds.sub = "[email protected]"
    client.authorization = @creds

    #metrics
    metric_views = Metric.new
    metric_views.expression = "ga:pageviews"
    metric_unique_views = Metric.new
    metric_unique_views.expression = "ga:uniquePageviews"

    #dimensions
    dimension = Dimension.new
    dimension.name = "ga:hostname"

    #range
    range = DateRange.new
    range.start_date = start_date
    range.end_date = end_date

    #sort
    orderby = OrderBy.new
    orderby.field_name = "ga:pageviews"
    orderby.sort_order = 'DESCENDING'

    rr = ReportRequest.new
    rr.view_id = VIEW_ID
    rr.metrics = [metric_views, metric_unique_views]
    rr.dimensions = [dimension]
    rr.date_ranges = [range]
    rr.order_bys = [orderby]

    grr = GetReportsRequest.new
    grr.report_requests = [rr]

    response = client.batch_get_reports(grr)

I would expect that there would be a stream_id property on the ReportRequest object that I could use instead of the view_id but that's not the case.


Solution

  • Your existing code uses the Google Analytics Reporting api to extract data from a Universal analytics account.

    Your new Google analytics property is a Google Analytics GA4 account. To extract data from that you need to use the Google analytics data api These are two completely different systems. You will not be able to just port it.

    You can find info on the new api and new library here: Ruby Client for the Google Analytics Data API

    $ gem install google-analytics-data