measurement-api
A lightweight asynchronous Python client for the Google Analytics 4 (GA4) Measurement Protocol.
Features
- ⚡ Asynchronous: Built on top of
httpxfor efficient, non-blocking requests. - 🔄 Connection Pooling: Supports async context manager syntax and custom
httpx.AsyncClientinjection to share/reuse TCP connections. - 🐛 Validation Mode: Integrates with GA4's validation server
/debug/mp/collectto 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.
-
Install dependencies:
uv sync --group dev
-
Run the test suite:
uv run pytest
-
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.
Metadata
Release files for measurement-api 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| measurement_api-0.2.0.tar.gz | 7.9 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| measurement_api-0.2.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 14.5 kB
Release files / measurement_api-0.2.0.tar.gz
| Download URL | measurement_api-0.2.0.tar.gz |
|---|---|
| Size | 7.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
328c3890a511e332706337db1498ae7a12e7e76b96c2134aa67d5662737823f4
|
|
BLAKE2b-256 checksum How to use checksums |
1c5af2392ac61b87b438f968767091fb7bc7a38326aef3b48d398cc5ef42ee44
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|
Release files / measurement_api-0.2.0-py3-none-any.whl
| Download URL | measurement_api-0.2.0-py3-none-any.whl |
|---|---|
| Size | 6.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d155a3a56df8b6c32fd799a65647d484355d8d3f00f2697e397c544d5f0e0133
|
|
BLAKE2b-256 checksum How to use checksums |
5be3ff0061c52dd055d2cacbc2c028cdbe3e4b439695ce02df21984b48f1f8d2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|
Security for measurement-api 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.