Run in Google Colab
|
View source on GitHub
|
Conversion reporting in the Google Analytics Data API (v1alpha) lets you generate reports focused on conversion events with support for different attribution models, such as Data-driven (DATA_DRIVEN) and Last click (LAST_CLICK).
Unlike standard event-based reports that provide raw counts of events (such as eventCount), conversion reports apply an attribution model to distribute credit among the marketing touchpoints (campaigns, sources, mediums, and channel groups) that led to a conversion. Conversion reports created with the Data API correspond to the attribution reports in the Advertising > Conversions section of the Google Analytics UI (see the Conversion performance report help center article).
This notebook demonstrates how to use the google-analytics-data Python client library (AlphaAnalyticsDataClient) to generate conversion reports:
- Configure the Colab environment
- Install and initialize the Python client
- Configure your GA property ID
- Generate a conversion report by campaign
- Retrieve available conversion actions for a property
- Re-create a Conversion Performance report
- Interactive conversion report builder
Step 0: Configure the Colab environment
Select an AUTH_METHOD in the form below and run the cell to configure Application Default Credentials (ADC) for a Google Cloud project with the Google Analytics Data API enabled. Leave SERVICE_ACCOUNT_EMAIL empty unless you select Service Account Impersonation.
| Authentication Option | When to use it |
|---|---|
Custom OAuth Client JSON (Browser) (default) |
Browser sign-in; no Service Account or local gcloud |
Custom OAuth Client JSON (gcloud --no-browser) |
Custom OAuth via local gcloud CLI |
Service Account Impersonation |
Keyless Service Account access (org-policy friendly) |
Service Account Key JSON |
Headless testing (requires careful key management) |
Expand an option below for step-by-step setup and technical details:
Custom OAuth Client JSON (Browser) (default)
- How it works: Leave
PROJECT_IDas-is (or enterPROJECT_IDto override), run the cell, uploadclient_secret.json, open the printed URL, and paste thehttp://localhost/?...redirect URL (orcode) from your browser's address bar. - When to use it: Default browser-only flow—works without a service account or local
gcloud. - Prerequisites:
- Enable the Data API.
- Configure Auth Platform branding (if External/Testing, add your email in Audience > Test users).
- In Auth Platform > Clients, click Create Client > Desktop app > Create, then Download JSON (guide).
- Grant your Google account GA Viewer access (Admin > Property access management).
- Under the hood: Exchanges the authorization code via OAuth 2.0 (
http://localhostredirect) and writes a user refresh token to ADC.
Custom OAuth Client JSON (gcloud --no-browser)
- How it works: Leave
PROJECT_IDas-is (or enterPROJECT_IDto override), run the cell, uploadclient_secret.json, run the printed--remote-bootstrapcommand locally, and paste back the output URL (guide). - When to use it: Alternative custom OAuth flow if you have
gcloudinstalled locally and prefer--remote-bootstrapover copyinglocalhostURLs. - Prerequisites:
- Follow steps 1–4 in
Custom OAuth Client JSON (Browser)above to download a Desktop appclient_secret.jsonand grant GA Viewer access. - Install the
gcloudCLI on your local machine.
- Follow steps 1–4 in
- Under the hood: Runs
gcloud auth application-default login --no-browser --client-id-file=...and saves the bootstrapped user token to ADC.
Service Account Impersonation
- How it works: Enter
SERVICE_ACCOUNT_EMAIL(and optionalPROJECT_IDoverride), run the cell, open the printed link to sign in, and paste the verification code (guide). - When to use it: Recommended keyless option when org policies block key files or restrict GA access to service accounts.
- Prerequisites:
- Enable the Data API and IAM Credentials API.
- In IAM > Service Accounts, select the service account > Permissions > Grant access and assign your user Service Account Token Creator (docs).
- Grant the service account email GA Viewer access (Admin > Property access management).
- Under the hood: Signs in your user with
cloud-platformscope only and writes an impersonation ADC config that exchanges your user token for short-lived service account tokens via IAM Credentials API.
Service Account Key JSON
- How it works: Leave
PROJECT_IDas-is (or enterPROJECT_IDto override), run the cell, and upload the JSON key file. - When to use it: Headless/shared testing with an existing key (warning: service account keys can become a security risk if not managed carefully).
- Prerequisites:
- Enable the Data API on the service account's project.
- In IAM > Service Accounts, select the service account > Keys > Add key > Create new key > JSON > Create (guide).
- Grant the service account email GA Viewer access (Admin > Property access management).
- Under the hood: Saves the uploaded key file to the runtime, sets
GOOGLE_APPLICATION_CREDENTIALS, and activates the service account ingcloudso client libraries mint tokens directly from the private key.
# @title Colab Authentication and Quota Project Setup { display-mode: "form" }
import json
import os
import urllib.parse
AUTH_METHOD = "Custom OAuth Client JSON (Browser)" # @param ["Custom OAuth Client JSON (Browser)", "Custom OAuth Client JSON (gcloud --no-browser)", "Service Account Impersonation", "Service Account Key JSON"]
PROJECT_ID = "YOUR_PROJECT_ID" # @param {type:"string"}
SERVICE_ACCOUNT_EMAIL = "" # @param {type:"string"}
SCOPES = [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/analytics.readonly",
]
SCOPES_CSV = ",".join(SCOPES)
def _optional_project_id() -> str:
project_id = PROJECT_ID.strip()
return "" if project_id == "YOUR_PROJECT_ID" else project_id
if AUTH_METHOD == "Custom OAuth Client JSON (Browser)":
from google.auth import _cloud_sdk
from google.colab import files
from google_auth_oauthlib.flow import InstalledAppFlow
project_id = _optional_project_id()
os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
print("Upload your OAuth Desktop client JSON file (client_secret.json):")
uploaded = files.upload()
if not uploaded:
raise ValueError("No OAuth client JSON file was uploaded.")
client_id_file = next(iter(uploaded))
try:
oauth_flow = InstalledAppFlow.from_client_secrets_file(
client_id_file, scopes=SCOPES
)
finally:
if os.path.exists(client_id_file):
os.remove(client_id_file)
oauth_flow.redirect_uri = "http://localhost"
auth_url, _ = oauth_flow.authorization_url(
access_type="offline", prompt="consent"
)
print(
"\n1. Open this URL in your browser and complete sign-in:\n\n"
f" {auth_url}\n\n"
"2. Your browser will redirect to http://localhost/?... (an 'unable to "
"connect' page is expected).\n"
" Copy the full http://localhost/... URL from your browser's address "
"bar (or just the code=... value)."
)
auth_response = input("Paste the redirect URL or authorization code: ").strip()
if "code=" in auth_response:
parsed = urllib.parse.urlparse(auth_response)
auth_code = urllib.parse.parse_qs(parsed.query).get("code", [""])[0]
else:
auth_code = urllib.parse.unquote(auth_response)
if not auth_code:
raise ValueError("Could not extract an authorization code from input.")
oauth_flow.fetch_token(code=auth_code)
creds = oauth_flow.credentials
adc_path = _cloud_sdk.get_application_default_credentials_path()
os.makedirs(os.path.dirname(adc_path), exist_ok=True)
with open(adc_path, "w", encoding="utf-8") as f:
json.dump(
{
"type": "authorized_user",
"client_id": creds.client_id,
"client_secret": creds.client_secret,
"refresh_token": creds.refresh_token,
},
f,
indent=2,
)
print(f"Saved Application Default Credentials to {adc_path}")
if project_id:
!gcloud auth application-default set-quota-project "{project_id}"
!gcloud config set project "{project_id}"
elif AUTH_METHOD == "Custom OAuth Client JSON (gcloud --no-browser)":
from google.colab import files
project_id = _optional_project_id()
os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
print("Upload your OAuth Desktop client JSON file (client_secret.json):")
uploaded = files.upload()
if not uploaded:
raise ValueError("No OAuth client JSON file was uploaded.")
client_id_file = next(iter(uploaded))
try:
!gcloud auth application-default login --no-browser --client-id-file="{client_id_file}" --scopes="{SCOPES_CSV}"
finally:
if os.path.exists(client_id_file):
os.remove(client_id_file)
if project_id:
!gcloud auth application-default set-quota-project "{project_id}"
!gcloud config set project "{project_id}"
elif AUTH_METHOD == "Service Account Impersonation":
project_id = _optional_project_id()
sa_email = SERVICE_ACCOUNT_EMAIL.strip()
if not sa_email:
raise ValueError(
"Please enter SERVICE_ACCOUNT_EMAIL for Service Account Impersonation."
)
os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
!gcloud auth application-default login --no-launch-browser --impersonate-service-account="{sa_email}" --scopes="{SCOPES_CSV}"
if project_id:
os.environ["GOOGLE_CLOUD_QUOTA_PROJECT"] = project_id
!gcloud config set project "{project_id}"
else:
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
elif AUTH_METHOD == "Service Account Key JSON":
from google.colab import auth
project_id = _optional_project_id()
auth.authenticate_service_account()
if project_id:
os.environ["GOOGLE_CLOUD_QUOTA_PROJECT"] = project_id
!gcloud config set project "{project_id}"
else:
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
Step 1: Install and initialize the Python client
Install the google-analytics-data Python client library and initialize AlphaAnalyticsDataClient from google.analytics.data_v1alpha. The client automatically detects and uses the Application Default Credentials configured in your environment.
%pip install --upgrade -q google-analytics-data
from google.analytics import data_v1alpha
# Create a client using Application Default Credentials
client = data_v1alpha.AlphaAnalyticsDataClient()
print("AlphaAnalyticsDataClient initialized successfully.")
Step 2: Configure your GA property ID
Enter your numeric Google Analytics Property ID below. You can find your Property ID in the Google Analytics UI under Admin > Property settings > Property details > Property ID.
# @title GA Property Settings
PROPERTY_ID = "YOUR_PROPERTY_ID" # @param {type:"string"}
if PROPERTY_ID == "YOUR_PROPERTY_ID" or not PROPERTY_ID.strip():
raise ValueError("Please provide a valid numeric GA Property ID.")
property_resource = f"properties/{PROPERTY_ID.strip()}"
print(f"Configured property resource: {property_resource}")
Step 3: Generate a conversion report by campaign
To run a conversion report, call the run_report method on AlphaAnalyticsDataClient. A request is treated as a conversion report if it queries one or more conversion metrics (such as allConversionsByConversionDate or allConversionsByInteractionDate), or if the conversion_spec field is populated in RunReportRequest.
The ConversionSpec object contains two fields:
conversion_actions: A list of conversion action resource names to include in the report (for example,["conversionActions/12345"]). If empty, all conversions are included.attribution_model: The attribution model to use (ConversionSpec.AttributionModel.DATA_DRIVENby default, orConversionSpec.AttributionModel.LAST_CLICK).
You can verify that a response was treated as a conversion report by checking that response.metadata.section is set to SECTION_ADVERTISING.
Scenario: All conversions by campaign name
The example below generates a conversion report showing conversions by campaignName over the last 30 days using the Data-driven attribution model (DATA_DRIVEN).
from IPython.display import display
import pandas as pd
AttributionModel = data_v1alpha.ConversionSpec.AttributionModel
def run_report_to_dataframe(
response: data_v1alpha.RunReportResponse,
) -> pd.DataFrame:
"""Converts a RunReportResponse into a pandas DataFrame and prints metadata."""
headers = [h.name for h in response.dimension_headers] + [
h.name for h in response.metric_headers
]
rows = [
[v.value for v in row.dimension_values]
+ [v.value for v in row.metric_values]
for row in response.rows
]
print(
f"Returned {len(rows):,} row(s) (total row_count: {response.row_count:,}). "
f"Section: {response.metadata.section.name}, "
f"currency: {response.metadata.currency_code}, "
f"time zone: {response.metadata.time_zone}"
)
return pd.DataFrame(rows, columns=headers)
# Build a conversion report request by campaign name
campaign_request = data_v1alpha.RunReportRequest(
property=property_resource,
dimensions=[data_v1alpha.Dimension(name="campaignName")],
metrics=[data_v1alpha.Metric(name="allConversionsByConversionDate")],
date_ranges=[
data_v1alpha.DateRange(start_date="30daysAgo", end_date="yesterday")
],
conversion_spec=data_v1alpha.ConversionSpec(
conversion_actions=[],
attribution_model=AttributionModel.DATA_DRIVEN,
),
)
campaign_response = client.run_report(request=campaign_request)
campaign_df = run_report_to_dataframe(campaign_response)
display(campaign_df.head(20))
Step 4: Retrieve available conversion actions for a property
To filter a conversion report to specific conversion events, you first need the valid conversion action resource names (such as conversionActions/12345) for your property.
Call the get_metadata method with properties/{PROPERTY_ID}/metadata. Be sure to specify your GA property ID (rather than 0) so the response includes the conversion actions configured for your property in metadata.conversions.
# Retrieve metadata for the property, including available conversion actions
metadata = client.get_metadata(
request=data_v1alpha.GetMetadataRequest(
name=f"{property_resource}/metadata"
)
)
conversions_df = pd.DataFrame(
[
{
"conversion_action": c.conversion_action,
"display_name": c.display_name,
}
for c in metadata.conversions
]
)
print(f"Found {len(conversions_df)} conversion action(s) for {property_resource}.")
display(conversions_df)
Step 5: Re-create a Conversion Performance report
Using the conversion actions retrieved in Step 4, you can re-create a report similar to the Conversion performance report in the Google Analytics UI (Advertising > Conversions > Conversion performance).
The request below queries defaultChannelGroup alongside advertising and conversion metrics (allConversionsByInteractionDate, advertiserAdCost, advertiserAdCostPerAllConversionsByInteractionDate, advertiserAdImpressions, advertiserAdClicks, advertiserAdCostPerClick, totalRevenueByInteractionDate, and returnOnAdSpendByInteractionDate).
Pass one or more conversion action resource names from Step 4 in selected_conversion_actions to filter the report, or leave the list empty ([]) to include all conversions.
# Optionally filter by specific conversion actions from Step 4,
# e.g. ["conversionActions/12345", "conversionActions/67890"].
# Leave empty ([]) to report on all conversions.
selected_conversion_actions: list[str] = []
performance_request = data_v1alpha.RunReportRequest(
property=property_resource,
dimensions=[data_v1alpha.Dimension(name="defaultChannelGroup")],
metrics=[
data_v1alpha.Metric(name="allConversionsByInteractionDate"),
data_v1alpha.Metric(name="advertiserAdCost"),
data_v1alpha.Metric(
name="advertiserAdCostPerAllConversionsByInteractionDate"
),
data_v1alpha.Metric(name="advertiserAdImpressions"),
data_v1alpha.Metric(name="advertiserAdClicks"),
data_v1alpha.Metric(name="advertiserAdCostPerClick"),
data_v1alpha.Metric(name="totalRevenueByInteractionDate"),
data_v1alpha.Metric(name="returnOnAdSpendByInteractionDate"),
],
date_ranges=[
data_v1alpha.DateRange(start_date="30daysAgo", end_date="yesterday")
],
conversion_spec=data_v1alpha.ConversionSpec(
conversion_actions=selected_conversion_actions,
attribution_model=AttributionModel.DATA_DRIVEN,
),
)
performance_response = client.run_report(request=performance_request)
performance_df = run_report_to_dataframe(performance_response)
display(performance_df)
Step 6: Interactive conversion report builder
Use the interactive form cell below to build a custom conversion report for your GA property. Enter comma-separated conversion dimension and metric API names, a date range, an attribution model (DATA_DRIVEN or LAST_CLICK), and optional comma-separated conversion_actions (leave blank to include all conversions).
# @title Run a Custom Conversion Report
dimensions = "defaultChannelGroup, campaignName" # @param {type:"string"}
metrics = "allConversionsByInteractionDate, totalRevenueByInteractionDate" # @param {type:"string"}
start_date = "30daysAgo" # @param {type:"string"}
end_date = "yesterday" # @param {type:"string"}
attribution_model = "DATA_DRIVEN" # @param ["DATA_DRIVEN", "LAST_CLICK"]
conversion_actions = "" # @param {type:"string"}
row_limit = 10000 # @param {type:"integer"}
def _split(names: str) -> list[str]:
return [name.strip() for name in names.split(",") if name.strip()]
custom_request = data_v1alpha.RunReportRequest(
property=property_resource,
dimensions=[data_v1alpha.Dimension(name=n) for n in _split(dimensions)],
metrics=[data_v1alpha.Metric(name=n) for n in _split(metrics)],
date_ranges=[
data_v1alpha.DateRange(start_date=start_date, end_date=end_date)
],
conversion_spec=data_v1alpha.ConversionSpec(
conversion_actions=_split(conversion_actions),
attribution_model=AttributionModel[attribution_model],
),
limit=row_limit,
)
custom_response = client.run_report(request=custom_request)
display(run_report_to_dataframe(custom_response))
Additional resources
- Conversion reporting basics
- Conversion Reports Schema (Advertising dimensions and metrics)
properties.runReportREST API Reference (v1alpha)properties.getMetadataREST API Reference (v1alpha)- Google Analytics Data API Quotas
- Python Client Library Reference (
google-analytics-data)
Run in Google Colab
View source on GitHub