Google Analytics Internal Server Error 500

Question:

I am trying to build an API call to retrieve google analytics data. This API call was working and now it returns the error :

<HttpError 500 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "Internal error encountered.". Details: "Internal error encountered.">

So the body of the code I got was from Google Analytics (GA from now on) documentation, so I dont understand what is going on. I also dont understand why it was working originally but now it is not.

Can anyone help me understand what I can do to get past this hurdle?

EDIT I removed the dimension "date" and it returns the data. However, the query builder in GA says I can use date as a dimension – so why is ga:date causing the call to break?

Code:

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import sys
import os
from mymodules import ODBC, SendEmail, MyLogging
from dotenv import load_dotenv, find_dotenv

package_name = os.path.basename(__file__)
load_dotenv(find_dotenv())
logger = MyLogging.NewLogger(__file__, use_cd=True)
logger.info(f'Beginning package GAUSers.py')

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'pathToclient_secrets.json'
VIEW_ID = 'viewID'

def initialize_analyticsreporting():
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  analytics = build('analyticsreporting', 'v4', credentials=credentials)
  return analytics

def get_report(analytics):
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges':[{'startDate':'2022-07-01','endDate':'yesterday'}],
          'metrics': [{'expression':'ga:users'},{'expression':'ga:newUsers'},{'expression':'ga:percentNewSessions'},{'expression':'ga:sessionsPerUser'}],
          'dimensions':[{'name':'ga.date'},{'name':'ga:UserType'},{'name':'ga:sessionCount'}]
        }]
      }
  ).execute()

def print_response(response):
  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])

    for row in report.get('data', {}).get('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):
        print('Date range:', str(i))
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print(metricHeader.get('name') + ':', value)
          
try:
    analytics = initialize_analyticsreporting()
    #error happens here
    response = get_report(analytics)
    print_response(response)

except Exception as e: 
    logger.info(str(e) + 'n')
    to_emails = os.getenv('Error_ToEmail').split(',')
    body = f'Error running package {package_name}n 
        Error message: ' + str(e)
    SendEmail.SendEmail(to_emails, 'Python Error', body)
Asked By: Doug Coats

||

Answers:

Google Analytics Internal Server Error 500

Is caused because you have a have a typo in your code

'dimensions':[{'name':'ga.date'},{'name':'ga:UserType'},{'name':'ga:sessionCount'}]
    }]

its ga:date not ga.date

Answered By: DaImTo