|---|---|
| [![](https://www.tensorflow.org/images/colab_logo_32px.png)Run in Google Colab](https://colab.research.google.com/github/googleanalytics/python-docs-samples/blob/main/google-analytics-data/notebooks/conversion-reports.ipynb) | [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png)View source on GitHub](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/notebooks/conversion-reports.ipynb) |

[Conversion reporting](https://developers.google.com/analytics/devguides/reporting/data/v1/conversions-api-basics.md.txt) in the [Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1.md.txt) (`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](https://analytics.google.com/analytics/web/) (see the [Conversion performance report](https://support.google.com/analytics/answer/14715749) help center article).

This notebook demonstrates how to use the [`google-analytics-data`](https://pypi.org/project/google-analytics-data/) Python client library (`AlphaAnalyticsDataClient`) to generate conversion reports:

0. [Configure the Colab environment](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/conversion-reports.md.txt#colab-config)
1. [Install and initialize the Python client](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/conversion-reports.md.txt#install)
2. [Configure your GA property ID](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/conversion-reports.md.txt#configure-property)
3. [Generate a conversion report by campaign](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/conversion-reports.md.txt#conversion-by-campaign)
4. [Retrieve available conversion actions for a property](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/conversion-reports.md.txt#retrieve-conversions)
5. [Re-create a Conversion Performance report](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/conversion-reports.md.txt#conversion-performance)
6. [Interactive conversion report builder](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/conversion-reports.md.txt#interactive-report)

> > [!NOTE]
> > **Note:** Conversion reporting is available in the [`v1alpha`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/runReport.md.txt) version of the Data API only. Alpha features may change in backward-incompatible ways.
>
> > [!CAUTION]
> > **Caution:** This feature may not be available to your Google Analytics property. The Google Analytics team is actively working to expand this feature to more properties. Reach out to your [support team](https://support.google.com/analytics/gethelp) if you have questions about the eligibility of your property.
>
## Step 0: Configure the Colab environment

Select an `AUTH_METHOD` in the form below and run the cell to configure [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) for a Google Cloud project with the [Google Analytics Data API enabled](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com). 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](https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys)) |

Expand an option below for step-by-step setup and technical details:

<br />

**`Custom OAuth Client JSON (Browser)`** *(default)*

<br />

- **How it works:** Leave `PROJECT_ID` as-is (or enter `PROJECT_ID` to override), run the cell, upload `client_secret.json`, open the printed URL, and paste the `http://localhost/?...` redirect URL (or `code`) from your browser's address bar.
- **When to use it:** Default browser-only flow---works without a service account or local `gcloud`.
- **Prerequisites:**
  1. Enable the [Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com).
  2. Configure [Auth Platform branding](https://console.cloud.google.com/auth/branding) (if External/Testing, add your email in [Audience \> Test users](https://console.cloud.google.com/auth/audience)).
  3. In [Auth Platform \> Clients](https://console.cloud.google.com/auth/clients), click **Create Client \> Desktop app \> Create** , then **Download JSON** ([guide](https://support.google.com/cloud/answer/6158849)).
  4. Grant your Google account [GA Viewer access](https://support.google.com/analytics/answer/9305788) (**Admin \> Property access management**).
- **Under the hood:** Exchanges the authorization code via OAuth 2.0 (`http://localhost` redirect) and writes a user refresh token to ADC.

<br />

<br />

<br />

**`Custom OAuth Client JSON (gcloud --no-browser)`**

<br />

- **How it works:** Leave `PROJECT_ID` as-is (or enter `PROJECT_ID` to override), run the cell, upload `client_secret.json`, run the printed `--remote-bootstrap` command locally, and paste back the output URL ([guide](https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login#--browser)).
- **When to use it:** Alternative custom OAuth flow if you have `gcloud` installed locally and prefer `--remote-bootstrap` over copying `localhost` URLs.
- **Prerequisites:**
  1. Follow steps 1--4 in `Custom OAuth Client JSON (Browser)` above to download a **Desktop app** `client_secret.json` and grant [GA Viewer access](https://support.google.com/analytics/answer/9305788).
  2. Install the [`gcloud` CLI](https://cloud.google.com/sdk/docs/install) on your local machine.
- **Under the hood:** Runs `gcloud auth application-default login --no-browser --client-id-file=...` and saves the bootstrapped user token to ADC.

<br />

<br />

<br />

**`Service Account Impersonation`**

<br />

- **How it works:** Enter `SERVICE_ACCOUNT_EMAIL` (and optional `PROJECT_ID` override), run the cell, open the printed link to sign in, and paste the verification code ([guide](https://cloud.google.com/docs/authentication/use-service-account-impersonation)).
- **When to use it:** Recommended keyless option when org policies block key files or restrict GA access to service accounts.
- **Prerequisites:**
  1. Enable the [Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com) and [IAM Credentials API](https://console.cloud.google.com/flows/enableapi?apiid=iamcredentials.googleapis.com).
  2. In [IAM \> Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts), select the service account \> **Permissions \> Grant access** and assign your user **Service Account Token Creator** ([docs](https://cloud.google.com/iam/docs/service-account-permissions#token-creator-role)).
  3. Grant the service account email [GA Viewer access](https://support.google.com/analytics/answer/9305788) (**Admin \> Property access management**).
- **Under the hood:** Signs in your user with `cloud-platform` scope only and writes an impersonation ADC config that exchanges your user token for short-lived service account tokens via IAM Credentials API.

<br />

<br />

<br />

**`Service Account Key JSON`**

<br />

- **How it works:** Leave `PROJECT_ID` as-is (or enter `PROJECT_ID` to 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](https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys))*.
- **Prerequisites:**
  1. Enable the [Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com) on the service account's project.
  2. In [IAM \> Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts), select the service account \> **Keys \> Add key \> Create new key \> JSON \> Create** ([guide](https://cloud.google.com/iam/docs/keys-create-delete)).
  3. Grant the service account email [GA Viewer access](https://support.google.com/analytics/answer/9305788) (**Admin \> Property access management**).
- **Under the hood:** Saves the uploaded key file to the runtime, sets `GOOGLE_APPLICATION_CREDENTIALS`, and activates the service account in `gcloud` so client libraries mint tokens directly from the private key.

<br />

<br />

> > [!NOTE]
> > **Note:** Outside Colab, follow the [Data API client library quickstart](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries) instead.
>
<br />

<button type="button" class="button-red button expand-control">Toggle code</button>

<br />

```python
# @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)
```

<br />

<br />

## Step 1: Install and initialize the Python client

Install the [`google-analytics-data`](https://pypi.org/project/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.

```python
%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](https://analytics.google.com/) under **Admin \> Property settings \> Property details \> Property ID**.

```python
# @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`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/runReport.md.txt) method on `AlphaAnalyticsDataClient`. A request is treated as a conversion report if it queries one or more [conversion metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/conversions-api-schema.md.txt#metrics) (such as `allConversionsByConversionDate` or `allConversionsByInteractionDate`), or if the [`conversion_spec`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/runReport.md.txt#ConversionSpec) 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_DRIVEN` by default, or `ConversionSpec.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`).

```python
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`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/getMetadata.md.txt) 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`.

```python
# 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.

```python
# 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](https://developers.google.com/analytics/devguides/reporting/data/v1/conversions-api-schema.md.txt), a date range, an attribution model (`DATA_DRIVEN` or `LAST_CLICK`), and optional comma-separated `conversion_actions` (leave blank to include all conversions).

```python
# @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](https://developers.google.com/analytics/devguides/reporting/data/v1/conversions-api-basics.md.txt)
- [Conversion Reports Schema (Advertising dimensions and metrics)](https://developers.google.com/analytics/devguides/reporting/data/v1/conversions-api-schema.md.txt)
- [`properties.runReport` REST API Reference (`v1alpha`)](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/runReport.md.txt)
- [`properties.getMetadata` REST API Reference (`v1alpha`)](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/getMetadata.md.txt)
- [Google Analytics Data API Quotas](https://developers.google.com/analytics/devguides/reporting/data/v1/quotas.md.txt)
- [Python Client Library Reference (`google-analytics-data`)](https://googleapis.dev/python/analyticsdata/latest/index.html)