Search code examples
pythongoogle-analyticsgoogle-apigoogle-oauthgoogle-api-python-client

Google Analytics with Python only shows the last dimension


So I'm using a slightly modified version of the Hello Analytics python script.

The only differences are that I have a few more "expressions" in the metrics and I'm trying to add a dimension. everything works fine except when I print out everything in the last for loop it only shows the last dimension.

So instead of getting a list of all the dimensions with there metrics I get only the last one.

ga:city: Ho Chi Minh City
ga:users: 19
ga:newUsers: 19
ga:sessionsPerUser: 1.263157894736842
ga:sessions: 24
ga:bounces: 18
ga:bounceRate: 75.0
ga:avgSessionDuration: 40.708333333333336

Here is the code sample

"""Hello Analytics Reporting API V4."""

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = '170823765'


def initialize_analyticsreporting():
  """Initializes the analyticsreporting service object.

  Returns:
    analytics an authorized analyticsreporting service object.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(CLIENT_SECRETS_PATH))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage('analyticsreporting.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)

  return analytics

def get_report(analytics):
    # Use the Analytics Service Object to query the Analytics Reporting API V4.
    return analytics.reports().batchGet(
        body={
            'reportRequests': [
                {
                    'viewId': VIEW_ID,
                    'dateRanges': [{'startDate': '30daysAgo', 'endDate': 'today'}],
                    'metrics': [
                        {'expression': 'ga:users'},
                        {'expression': 'ga:newUsers'},
                        {'expression': 'ga:sessionsPerUser'},
                        {'expression': 'ga:sessions'},
                        {'expression': 'ga:bounces'},
                        {'expression': 'ga:bounceRate'},
                        {'expression': 'ga:avgSessionDuration'},
                    ],
                    "dimensions": [
                        {"name": "ga:city"}
                    ]
                }
            ]
        }
    ).execute()


def print_response(response):
    """Parses and prints the Analytics Reporting API V4 response"""

    for report in response.get('reports', []):

        columnHeader = report.get('columnHeader', {})
        dimensionHeaders = columnHeader.get('dimensions', [])
        metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
        rows = report.get('data', {}).get('rows', [])


        for row in rows:
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])

        for header, dimension in zip(dimensionHeaders, dimensions):
            print(header + ': ' + dimension)

        for i, values in enumerate(dateRangeValues):
            for metricHeader, value in zip(metricHeaders, values.get('values')):
                print(metricHeader.get('name') + ': ' + value)


def main():

  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

if __name__ == '__main__':
  main()

I'm new to both Google Analytics and Python so I apologize if this is a no-brainier question.

Thanks


Solution

  • It was an error in my spacing. not used to working with python missed the fact that I should have indented the part were it goes through the results and prints them out.

    So instead of

        for row in rows:
            dimensions = row.get('dimensions', [])
            dateRangeValues = row.get('metrics', [])
    
        for header, dimension in zip(dimensionHeaders, dimensions):
            print(header + ': ' + dimension)
    
        for i, values in enumerate(dateRangeValues):
    
            for metricHeader, value in zip(metricHeaders, values.get('values')):
                print(metricHeader.get('name') + ': ' + value)
    

    It should be

     for row in rows:
                dimensions = row.get('dimensions', [])
                dateRangeValues = row.get('metrics', [])
    
                for header, dimension in zip(dimensionHeaders, dimensions):
                    print(header + ': ' + dimension)
    
                for i, values in enumerate(dateRangeValues):
    
                    for metricHeader, value in zip(metricHeaders, values.get('values')):
                        print(metricHeader.get('name') + ': ' + value)