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.

Made in Ukraine

PyPI Downloads PyPI - License PyPI - Version

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(
        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
    

AI Agent Skill

This repository includes a specialized skill for AI agents. It helps the agent provide expert assistance in writing Python code and integrating this library into your projects.

To install the skill, run:

npx skills add https://github.com/BogdanovychA/measurement-api --skill measurement-api

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.2.0.tar.gz (7.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.2.0-py3-none-any.whl (6.7 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for measurement_api-0.2.0.tar.gz
Algorithm Hash digest
SHA256 328c3890a511e332706337db1498ae7a12e7e76b96c2134aa67d5662737823f4
MD5 a1c1d09b9088bd8535bfa2a1003a5529
BLAKE2b-256 1c5af2392ac61b87b438f968767091fb7bc7a38326aef3b48d398cc5ef42ee44

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for measurement_api-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d155a3a56df8b6c32fd799a65647d484355d8d3f00f2697e397c544d5f0e0133
MD5 7ea1ea691a3727715c14071222845d40
BLAKE2b-256 5be3ff0061c52dd055d2cacbc2c028cdbe3e4b439695ce02df21984b48f1f8d2

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