Amplitude Python SDK
The official Amplitude backend Python SDK provides server-side instrumentation for tracking analytics events. Currently at version 1.2.3, it offers functionalities to send events, manage user properties, and track revenue, with regular patch and minor releases to enhance stability and features.
Warnings
- breaking Major version updates (e.g., v1.x to v2.x) may introduce significant changes to public interfaces, behaviors, or semantics. Always review upgrade guidelines carefully when moving to a new major version.
- gotcha Events are queued in memory and sent in batches. If your application exits immediately after calling `track()`, events might not be sent. You must call `client.flush()` to ensure all buffered events are delivered.
- gotcha By default, data is sent to Amplitude's US servers. If your project requires EU data residency, you must explicitly configure the `server_zone` to 'EU' during SDK initialization.
- gotcha Using an incorrect API key or having multiple SDK instances (e.g., different Amplitude projects within the same application) without proper separation can lead to events not being ingested or being sent to the wrong project.
- gotcha Amplitude has a minimum length requirement for `user_id` and `device_id`. Providing IDs shorter than this minimum can result in 400 errors and events not being tracked.
- gotcha Amplitude enforces a throttling limit of 30 events per user or device per second. Exceeding this limit can cause events to be throttled and logged with a warning, leading to incomplete data.
Install
-
pip install amplitude-analytics
Imports
- Amplitude
from amplitude import Amplitude
- BaseEvent
from amplitude import BaseEvent
- Identify
from amplitude import Identify
Quickstart
import os
from amplitude import Amplitude, BaseEvent, Identify
import time
AMPLITUDE_API_KEY = os.environ.get("AMPLITUDE_API_KEY", "YOUR_AMPLITUDE_API_KEY")
# Initialize the SDK
# For EU data residency, add: server_zone='EU' to Amplitude(API_KEY, ...)
amplitude = Amplitude(AMPLITUDE_API_KEY)
# Example: Configure for EU data residency (uncomment if applicable)
# amplitude.configuration.server_zone = 'EU'
# Create and track a basic event
print("Tracking a 'User Logged In' event...")
event = BaseEvent(
event_type="User Logged In",
user_id="user_123",
device_id="device_abc",
event_properties={
"login_method": "email",
"timestamp": int(time.time())
}
)
amplitude.track(event)
# Identify a user and set/update user properties
print("Setting user properties for 'user_123'...")
identify = Identify()
identify.set("plan", "premium")
identify.set_once("initial_referrer", "google") # Set only once
identify.add("login_count", 1) # Increment a property
amplitude.identify("user_123", identify)
# Important: Flush events before application exit to ensure delivery
print("Flushing events...")
amplitude.flush()
print("Events sent and flushed. Check your Amplitude project.")