GATest.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Hello Analytics Reporting API V4."""
  2. from apiclient.discovery import build
  3. from oauth2client.service_account import ServiceAccountCredentials
  4. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  5. KEY_FILE_LOCATION = ''
  6. VIEW_ID = '<REPLACE_WITH_VIEW_ID>'
  7. def initialize_analyticsreporting():
  8. """Initializes an Analytics Reporting API V4 service object.
  9. Returns:
  10. An authorized Analytics Reporting API V4 service object.
  11. """
  12. credentials = ServiceAccountCredentials.from_json_keyfile_name(
  13. KEY_FILE_LOCATION, SCOPES)
  14. # Build the service object.
  15. analytics = build('analyticsreporting', 'v4', credentials=credentials)
  16. return analytics
  17. def get_report(analytics):
  18. """Queries the Analytics Reporting API V4.
  19. Args:
  20. analytics: An authorized Analytics Reporting API V4 service object.
  21. Returns:
  22. The Analytics Reporting API V4 response.
  23. """
  24. return analytics.reports().batchGet(
  25. body={
  26. 'reportRequests': [
  27. {
  28. 'viewId': VIEW_ID,
  29. 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
  30. 'metrics': [{'expression': 'ga:sessions'}],
  31. 'dimensions': [{'name': 'ga:country'}]
  32. }]
  33. }
  34. ).execute()
  35. def print_response(response):
  36. """Parses and prints the Analytics Reporting API V4 response.
  37. Args:
  38. response: An Analytics Reporting API V4 response.
  39. """
  40. for report in response.get('reports', []):
  41. columnHeader = report.get('columnHeader', {})
  42. dimensionHeaders = columnHeader.get('dimensions', [])
  43. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  44. for row in report.get('data', {}).get('rows', []):
  45. dimensions = row.get('dimensions', [])
  46. dateRangeValues = row.get('metrics', [])
  47. for header, dimension in zip(dimensionHeaders, dimensions):
  48. print(header + ': ', dimension)
  49. for i, values in enumerate(dateRangeValues):
  50. print('Date range:', str(i))
  51. for metricHeader, value in zip(metricHeaders, values.get('values')):
  52. print(metricHeader.get('name') + ':', value)
  53. def main():
  54. analytics = initialize_analyticsreporting()
  55. response = get_report(analytics)
  56. print_response(response)
  57. if __name__ == '__main__':
  58. main()