Search code examples
pythongoogle-analyticsgoogle-analytics-api

How to get records with pagination using google analytics python API


I am using google analytics python API to retrieve the records. The google analytics API is giving a maximum of 10000 records for a request. I have more than 10k records where I need to use pagination to get all the records. Below is the code that I used

def get_report(analytics):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '2020-07-02', 'endDate': '2020-07-09'}],
          'pageSize': 10000,
          'metrics':[{'expression': 'ga:pageViews'}],
          'dimensions':[{'name': 'ga:dimension1'}, {'name': 'ga:dimension2'}],
        }]
      }
  ).execute()

How to make this function work for pagination where I can get the entire data which has more than 10k records?


Solution

  • First, you can usenextPageToken parameter in response and pageToken parameter in reportRequest. See details in the documentation: Also, you're limiting your response by using pagesize parameter. You may get as much as 100,000 rows max in a single report request.