# RudderStack Python SDK Reference

<!-- Page Type: Reference Documentation -->

<!-- Documentation Rating: Technical Accuracy Score: 95, Comprehensibility Score: 90, Overall Score: 93 -->

<!-- Table of Contents:
1. Introduction
2. Prerequisites
3. Install the Python SDK
4. Initialize the SDK
5. Send events
   5.1 Identify
   5.2 Track
   5.3 Page
   5.4 Screen
   5.5 Group
   5.6 Alias
6. Gzip requests
7. Flush events
8. Handle errors
9. FAQ
-->

RudderStack's **Python SDK** provides a comprehensive API for tracking and sending events from your Python applications to various destinations.

For implementation examples and source code, see the SDK's [GitHub repository](https://github.com/rudderlabs/rudder-sdk-python).

{{< version-badge registry="pypi" package="rudder-sdk-python" fallback="2.1.4" href="https://pypi.org/project/rudder-sdk-python/" >}}

## Prerequisites

- A Python source [set up in the RudderStack dashboard]({{< ref "dashboard-guides/sources.md#add-a-source" >}})
- The {{< glossary_tooltip "write-key" >}} for your Python source — you can find it the **Setup** tab of the source
- The {{< glossary_tooltip "data-plane-url" >}} associated with your RudderStack workspace

## Installation

To install the RudderStack Python SDK using [**pip**](https://pip.pypa.io/en/stable/), run the following command:

```bash
pip install rudder-sdk-python
```

## Initialization

To initialize the SDK, run the following code snippet:

```python
import rudderstack.analytics as rudder_analytics

rudder_analytics.write_key = WRITE_KEY
rudder_analytics.dataPlaneUrl = DATA_PLANE_URL
```

## Configuration options

The Python SDK provides the following configuration options:

| Parameter | Description | Default value |
| :----------| :------------| :-------------|
| `on_error` | Callback for exception thrown while uploading the messages. | `None` |
| `debug` | The SDK prints the logs if set to `True`. | `False` |
| `send` | The SDK does not send the data to the RudderStack backend if set to `False`. | `True` |
| `sync_mode` | The SDK sends the data immediately instead of queueing it, if set to `True`. | `False` |
| `max_queue_size` | Maximum queue size the SDK uses to enqueue the events. | `10000` |
| `gzip` | The SDK disables gzipping the event data if set to `False`. | `True` |
| `timeout` | The timeout for sending POST requests to the RudderStack backend. | `15` |
| `max_retries` | Maximum number of retry requests the SDK makes to the RudderStack backend. | `10` |
| `upload_interval` | Maximum duration between two upload (flush) activities. | `0.5s` |
| `upload_size` | Number of events in the queue that triggers a flush. | `100` |

## Event methods

{{< warning >}}
The Python SDK does not persist user state. You must specify either `user_id` or `anonymous_id` with every event API call.
{{< /warning >}}

### Identify

The [`identify`]({{< ref "event-spec/standard-events/identify.md" >}}) method records user identity and traits.

**Example**:

```python
rudder_analytics.identify('1hKOmRA4GRlm', {
    'email': 'alex@example.com',
    'name': 'John Doe',
    'friends': 16
})
```

**Parameters**:

| Field | Type | Description |
| :------------- | :------- |  :---------------- |
| `user_id` <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`anonymous_id`** is absent.</span>     | String   | Unique identifier for a user in your database. |
| `anonymous_id`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`user_id`** is absent.</span> | String   |  Identifier set in cases where no unique user identifier is available. |
| `traits`       | Object   | Dictionary of the user's traits like `name`, `email`, etc. |
| `context`      | Object   |  Optional dictionary of information that provides context about the event.  |
| `integrations` | Object   | Optional dictionary containing the destinations to be enabled or disabled. |
| `timestamp`    | Datetime   | The timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server. |

### Track

The [`track`]({{< ref "event-spec/standard-events/track.md" >}}) method records user actions and their associated properties.

**Method signature**:

```python
rudder_analytics.track(user_id=None, anonymous_id=None, event=None, properties=None, context=None, integrations=None, timestamp=None)
```

**Parameters**:

| Field | Type | Description |
| :------------- | :------- |  :---------------- |
| `user_id` <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`anonymous_id`** is absent.</span>     | String   | Unique identifier for a user in your database. |
| `anonymous_id`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`user_id`** is absent.</span> | String   |  Identifier set in cases where no unique user identifier is available. |
| `event`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span> | String | Name of the event. |
| `properties`   | Object | Optional dictionary of the properties associated with the event. |
| `context`      | Object   |  Optional dictionary of information that provides context about the event.  |
| `integrations` | Object   | Optional dictionary containing the destinations to be enabled or disabled. |
| `timestamp`    | Datetime   | The timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server. |

**Example**:

```python
rudder_analytics.track('1hKOmRA4GRlm', 'Article Read', {
    'title': 'The Independence',
    'subtitle': 'Story of the Weak',
    'author': 'John Doe'
})
```

### Page

The [`page`]({{< ref "event-spec/standard-events/page.md" >}}) call records page views in your application along with the relevant page information.

**Example**:

```python
rudder_analytics.page('1hKOmRA4GRlm', 'Documentation', 'Sample Documentation', {
    'url': 'http://rudderstack.com'
})
```

**Parameters**:

| Field | Type | Description |
| :------------- | :------- |  :---------------- |
| `user_id` <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`anonymous_id`** is absent.</span>     | String   | Unique identifier for a user in your database. |
| `anonymous_id`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`user_id`** is absent.</span> | String   |  Identifier set in cases where no unique user identifier is available. |
| `name`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span>      | String | Name of the viewed page. |
| `category`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span>      | String | Category of the viewed page. |
| `properties`   | Object | Optional dictionary of the properties associated with the page, like `url` or `referrer`.   |
| `context`      | Object   |  Optional dictionary of information that provides context about the event.  |
| `integrations` | Object   | Optional dictionary containing the destinations to be enabled or disabled. |
| `timestamp`    | Datetime   | The timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server. |

### Screen

The [`screen`]({{< ref "event-spec/standard-events/screen.md" >}}) call records screen views in your mobile app.

**Example**:

```python
rudder_analytics.screen('userid', 'Settings', 'Brightness', {
    'from': 'Settings Screen'
})
```

**Parameters**:

| Field | Type | Description |
| :------------- | :------- |  :---------------- |
| `user_id` <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`anonymous_id`** is absent.</span>     | String   | Unique identifier for a user in your database. |
| `anonymous_id`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`user_id`** is absent.</span> | String   |  Identifier set in cases where no unique user identifier is available. |
| `name`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span>      | String | Name of the viewed screen. |
| `category`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span>      | String | Category of the viewed screen. |
| `properties`   | Object | Optional dictionary of the properties associated with the screen, like `url` or `referrer`.   |
| `context`      | Object   |  Optional dictionary of information that provides context about the event.  |
| `integrations` | Object   | Optional dictionary containing the destinations to be enabled or disabled. |
| `timestamp`    | Datetime   | The timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server. |

### Group

The [`group`]({{< ref "event-spec/standard-events/group.md" >}}) call links an identified user with a group and records any custom traits associated with that group.

**Example**:

```python
rudder_analytics.group('1hKOmRA4GRlm', '12', {
    'name': 'Company',
    'domain': 'IT'
})
```

**Parameters**:

| Field | Type | Description |
| :------------- | :------- |  :---------------- |
| `user_id` <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`anonymous_id`** is absent.</span>     | String   | Unique identifier for a user in your database. |
| `anonymous_id`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required, if **`user_id`** is absent.</span> | String   |  Identifier set in cases where no unique user identifier is available. |
| `group_id`  <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span>    | String   | Unique identifier for the group in your database.    |
| `traits`       | Object   | Dictionary of the group's traits like `name` or `email`. |
| `context`      | Object   |  Optional dictionary of information that provides context about the event.  |
| `integrations` | Object   | Optional dictionary containing the destinations to be enabled or disabled. |
| `timestamp`    | Datetime   | The timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server. |

### Alias

{{< warning >}}
RudderStack supports sending `alias` events only to some destinations. See the [destination-specific documentation]({{< ref "destinations/streaming-destinations/_index.md" >}}) for more information.
{{< /warning >}}

The [`alias`]({{< ref "event-spec/standard-events/alias.md" >}}) call merges different identities of a known user.

**Example**:

```python
rudder_analytics.alias('previous_id', 'user_id')
```

**Parameters**:

| Field | Type | Description |
| :------------- | :------- |  :---------------- |
| `user_id` <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span>     | String   | Unique identifier for a user in your database. |
| `previous_id` <br/> <span style="color: #4D4DFF;font-size:12px;">Required</span>  | String   | Previous identifier for the user. |
| `context`      | Object   |  Optional dictionary of information that provides context about the event.  |
| `integrations` | Object   | Optional dictionary containing the destinations to be enabled or disabled. |
| `timestamp`    | Datetime   | The timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server. |

## Event flushing

The Python SDK batches the events and flushes them in the background, for faster and more efficient operation. By default, the SDK flushes a batch of 100 events every 0.5 seconds since the last flush.

You can control the event flushing by tweaking the following parameters:

| Parameter | Description | Default value |
| :----------| :------------| :-------------|
| `max_queue_size` | Maximum queue size the SDK uses to enqueue the events. | `10000` |
| `upload_interval` | Maximum duration between two upload (flush) activities. | `0.5s` |


### Manual flush

You can also flush the events explicitly by using the SDK's `flush()` method to make sure no events are left in the queue.

{{< warning >}}
The SDK blocks the calling thread until all messages are flushed from the queue. Hence, avoid using it as a part of your request lifecycle.
{{< /warning >}}

A sample flush call is shown below:

```python
rudder_analytics.flush()
```

## Event request compression

{{< warning >}}
Self-hosted data planes require [rudder-server](https://github.com/rudderlabs/rudder-server) version 1.4+ to support event request compression.
{{< /warning >}}

The Python SDK automatically gzips requests. However, you can disable this feature by setting the `gzip` parameter to `false` while initializing the SDK:

```python
import rudderstack.analytics as rudder_analytics

rudder_analytics.write_key = WRITE_KEY
rudder_analytics.dataPlaneUrl = DATA_PLANE_URL
rudder_analytics.gzip = False
```

## Error handling

The Python SDK provides a `on_error` callback that lets you handle any errors that might occur when sending events.

```python
def on_error(error, events):
    print("Error response:", error)

rudder_analytics.on_error = on_error
```

{{< warning >}}
The `on_error` callback only returns the errors that occur with the HTTP requests to the RudderStack gateway. It does not return any errors that occur while sending data to your downstream destinations.
{{< /warning >}}

The `on_error` callback function takes the following objects:

| Object | Type |
| :------ | :--- |
| error | [APIError](https://github.com/rudderlabs/rudder-sdk-python/blob/73f1a72bfa72b75413498eabaaf4ac4a7ab2fdba/rudderstack/analytics/request.py#L65) type.  |
| events | List of events that failed while being sent to the RudderStack data plane (backend). It is the raw events data which gets buffered in the SDK. Also, each event contains all the fields included in it. |

The below table lists some of the common request responses:

| Status | Code |
| :------ | :--- |
| OK | 200  |
| Request has neither `anonymousId` nor `userId` | 400  |
| Invalid write key | 401  |
| Invalid JSON | 400  |

## FAQ

#### How does the Python SDK handle events larger than 32KB?

The Python SDK drops any events greater than 32KB.

#### Does the Python SDK support event ordering?

The Python SDK does not support event ordering by default.

<br />
