Reputation: 11
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Replace the values in the following line with your own credentials
creds = service_account.Credentials.from_service_account_file(r"C:\Users\xxxx\xxx\xxx\xxx.json")
# Create a Google Analytics Data API client
analytics_service = build('analyticsdata', 'v1beta', credentials=creds)
# Define the Google Analytics Data API request for a GA4 property
request = {
'property': 'properties/xxxxx',
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'dimensions': [{'name': 'date'}],
'metrics': [{'name': 'activeUsers'}]
}
# Call the Google Analytics Data API using the request
try:
response = analytics_service.properties().runReport(body={'request': request}).execute()
# Print the response
print(response)
except Exception as e:
print(e)
I've given the service account appropriate access to Google Analytics 4's admin and on IAM. I've also activated the Google Analytics Data API on GCP but I keep getting the below error,
Missing required parameter "property"
I was expecting to pull data from the property ID I had entered
Upvotes: 1
Views: 636
Reputation: 615
Just wanted to circle back to this because I ran into this issue last night. I think Google is often updating it's documentation.
Check out the documentation for:
This is the request pattern that ultimately worked for me:
def _get_report_ga4(client, property_id, start_date, end_date):
request = RunReportRequest(
property=f"properties/{property_id}",
date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
metrics=[Metric(name="activeUsers"), Metric(name="sessions")]
)
print("Request:", request)
return client.run_report(request=request)
You also are going to want to check for these imports.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
from run_report import print_run_report_response
Upvotes: 0
Reputation: 534
Try this:
# Define the Google Analytics Data API request for a GA4 property
# Here is where it went right for me
request = {
'property': 'properties/xxxxx',
'requestBody': {
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'dimensions': [{'name': 'date'}],
'metrics': [{'name': 'activeUsers'}]
}
}
Upvotes: 0