Skip to main content

A lightweight asynchronous Python client for the Google Analytics 4 Measurement Protocol

Project description

measurement-api

A lightweight asynchronous Python client for the Google Analytics 4 (GA4) Measurement Protocol.

PyPI version Python versions License: MIT

Features

  • Asynchronous: Built on top of httpx for efficient, non-blocking requests.
  • 🔄 Connection Pooling: Supports async context manager syntax and custom httpx.AsyncClient injection to share/reuse TCP connections.
  • 🐛 Validation Mode: Integrates with GA4's validation server /debug/mp/collect to verify your payloads without logging dummy events in production.
  • 📦 Complex Event Parameters: Supports nested structures like lists (e.g. for E-commerce tracking items), dictionaries, and primitives.

Installation

Install using pip:

pip install measurement-api

Or using uv:

uv add measurement-api

Quickstart

Basic Async Usage

import asyncio
from measurement_api import MeasurementAPI

async def main():
    # Initialize the client
    api = MeasurementAPI(
        m10t_id="G-XXXXXXXXXX",
        secret_key="your_api_secret_key"
    )

    # Log an event
    success = await api.log_event(
        client_id="user_12345",
        event_name="button_click",
        button_id="submit_form",
        page_url="https://example.com"
    )

    if success:
        print("Event sent successfully!")
    else:
        print("Failed to send event.")

asyncio.run(main())

Advanced Usage

Context Manager (Connection Reuse)

When sending multiple events, use the async context manager to reuse the HTTP client's connection pool. This avoids the overhead of establishing a new TCP/TLS connection for every single event.

import asyncio
from measurement_api import MeasurementAPI

async def main():
    async with MeasurementAPI("G-XXXXXXXXXX", "your_secret") as api:
        # Both events share the same connection pool
        await api.log_event("user_1", "view_item", item_name="T-Shirt")
        await api.log_event("user_1", "add_to_cart", item_name="T-Shirt")

asyncio.run(main())

Passing a Custom httpx.AsyncClient

If your application already manages a global HTTP client (e.g. in FastAPI or Sanic), you can inject it directly:

import httpx
from measurement_api import MeasurementAPI

async def send_analytics():
    # Inject your own shared client
    async with httpx.AsyncClient() as shared_client:
        api = MeasurementAPI(
            "G-XXXXXXXXXX",
            "your_secret",
            client=shared_client
        )

        # This will not close the injected client on exit or completion
        await api.log_event("user_1", "purchase", value=99.99)

Debug & Validation Mode

To validate your event structure against Google's GA4 validation server, initialize the client with debug=True. Note: Events sent to the validation server do not show up in GA4 reports.

from measurement_api import MeasurementAPI

api = MeasurementAPI("G-XXXXXXXXXX", "your_secret", debug=True)

# This request goes to https://www.google-analytics.com/debug/mp/collect
# Returns True if validation passes, False if there are validation warnings/errors
success = await api.log_event("user_1", "purchase", items=[{"item_id": "SKU_123"}])

Development & Testing

Running Tests

We use pytest and respx to test the client offline without sending actual requests to Google Analytics.

  1. Install dependencies:

    uv sync --group dev
    
  2. Run the test suite:

    uv run pytest
    
  3. Run linting checks:

    uv run ruff check
    

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

measurement_api-0.1.0.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

measurement_api-0.1.0-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file measurement_api-0.1.0.tar.gz.

File metadata

  • Download URL: measurement_api-0.1.0.tar.gz
  • Upload date:
  • Size: 6.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for measurement_api-0.1.0.tar.gz
Algorithm Hash digest
SHA256 479c1e900daa66f7c417051f28634dad756c0577ccab92522c890d6708a01f01
MD5 02144e2c12ada201377869d03184817b
BLAKE2b-256 e53e286e682fe6d0f3d4d4714bcb0f3b8a0b999e931c18a0943c3174512ed3a3

See more details on using hashes here.

File details

Details for the file measurement_api-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for measurement_api-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2c4420f2096f1d9160edbd3e882c193cf0cc403c9227622e80289ed65f6a11a1
MD5 3b8ac42058f4a5540e77d63d6fa62e9a
BLAKE2b-256 87054d0ac3a9abfec78d7694ac898bfb568cb0105c1efc9a7c353d93c68ffe65

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page