---
source_url: https://www.pubnub.com/docs/sdks/python/api-reference/message-persistence
title: Message Persistence API for Python SDK
updated_at: 2026-11-25T12:28:11.000Z
sdk_name: PubNub Python SDK
sdk_version: 10.9.1
description: "Reference for the PubNub Python SDK Message Persistence methods: fetch_messages(), delete_messages(), and message_counts(). Covers the history() method, whose use is not recommended."
---

# Message Persistence API for Python SDK

PubNub Python SDK, use the latest version: 10.9.1

Install:

```bash
pip install pubnub==10.9.1
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

The PubNub Python SDK reads, deletes, and counts the messages that Message Persistence stores, with `fetch_messages()`, `delete_messages()`, and `message_counts()`. Message Persistence must be enabled on the keyset before you store or read history, and new keysets don't enable it by default.

Each builder method has a keyword argument of the same name, except where a table says otherwise. A failed request raises a `PubNubException` from `.sync()`. With `.pn_async(callback)`, the callback receives a `status` where `status.is_error()` returns `True`.

:::note Request execution and return values
You can decide whether to perform the Python SDK operations synchronously or asynchronously.
* `.sync()` returns an `Envelope` object, which has two fields: `Envelope.result`, whose type differs for each API, and `Envelope.status` of type `PnStatus`.
   ```python
   pubnub.publish() \
       .channel("myChannel") \
       .message("Hello from PubNub Python SDK") \
       .sync()
   ```
* `.pn_async(callback)` returns `None` and passes the values of `Envelope.result` and `Envelope.status` to a callback you must define beforehand.
   ```python
   def my_callback_function(result, status):
       print(f'TT: {result.timetoken}, status: {status.category.name}')

   pubnub.publish() \
       .channel("myChannel") \
       .message("Hello from PubNub Python SDK") \
       .pn_async(my_callback_function)
   ```
:::

Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md).

You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.

You can retrieve the following:

* Messages
* Message reactions
* Files (using the File Sharing API)

## Fetch history

This method requires that the Message Persistence add-on is [enabled](https://www.pubnub.com/docs/faq/getting-started.md#how-do-i-enable-an-add-on-feature-on-my-keyset) for your key in the [Admin Portal](https://admin.pubnub.com/). Related: [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md).

`fetch_messages()` returns the messages that Message Persistence stores for one or more channels, using a PubNub client for Python.

The `start` and `end` timetokens control which messages the call returns and in what order.

* If you specify only `start`, the call returns messages older than that timetoken, because `start` is the newer, exclusive boundary of the query.
* If you specify only `end`, the call returns messages with a timetoken equal to or newer than `end`, because `end` is the older, inclusive boundary of the query.

:::warning How to use the start and end parameters
PubNub retrieves messages by searching **backward through time** (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:
* **start** is the **newer** boundary (higher timetoken value) - search begins here, **exclusive**
* **end** is the **older** boundary (lower timetoken value) - search stops here, **inclusive**
When you provide both parameters, `start` must be a **higher** timetoken than `end`.
```mermaid
graph LR
    A(["9:00 AM<br/>(oldest)"]) -->|"time flows →"| B["end = 10:00 AM<br/>older boundary<br/>inclusive ✓"]
    B --> C["messages<br/>retrieved"]
    C --> D["start = 11:00 AM<br/>newer boundary<br/>exclusive ✗"]
    D -->|"time flows →"| E(["11:59 AM<br/>(newest)"])
    D -.->|"◄ API searches backward"| B
    style A fill:#f8f9fa,stroke:#6c757d,color:#495057
    style E fill:#f8f9fa,stroke:#6c757d,color:#495057
    style B fill:#d4edda,stroke:#28a745,color:#000
    style C fill:#cce5ff,stroke:#004085,color:#000
    style D fill:#fff3cd,stroke:#856404,color:#000
```
9:00 AM10:00 AM11:00 AM11:59 AM
Results are always returned in oldest-first order.
:::

A single history call returns up to 100 messages for one channel, or up to 25 messages per channel across as many as 500 channels. If more messages match the time range, call again and set `start` to the timetoken of the oldest message in the previous response. The `start` and `end` parameters take an int, so convert a timetoken string with `int()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | str or list of str | Yes | n/a | IDs of the channels to fetch messages from, up to 500 channels. Pass a list of channel names or one string. A string is split on commas, so `"ch1,ch2"` names two channels. With more than one channel and include_message_actions set to True fails validation with the message `History can return message action data for a single channel only. Either pass a single channel or disable the include_message_actions flag`. |
| count | int | Optional | n/a | Number of messages to return for each channel. The default is `100` for one channel, and `25` for several channels or with `include_message_actions` set to `true`. The SDK lowers a larger value to that default. The builder also accepts `maximum_per_channel()` as an alias. |
| start | int | Optional | n/a | Timetoken that sets the newer boundary of the query (exclusive). Retrieval begins at this timetoken and moves backward in time. With `end`, `start` must be a higher timetoken than `end`. |
| end | int | Optional | n/a | Timetoken that sets the older boundary of the query (inclusive). Retrieval stops at this timetoken. With `start`, `end` must be a lower timetoken than `start`. |
| include_meta | bool | Optional | `False` | Whether each returned message includes the metadata that its publisher set at publish time, in the `meta` property. |
| include_message_actions | bool | Optional | `False` | Whether the response includes the message actions of each message, which limits the call to one channel and 25 messages. |
| include_message_type | bool | Optional | n/a | Whether each returned message includes its PubNub message type in the `message_type` property. |
| include_custom_message_type | bool | Optional | n/a | Whether the request asks PubNub to include the custom message type of each message. The SDK sends the flag, but the items of the result do not expose a custom message type. Only the builder form sets it. For the background, see [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md). |
| include_uuid | bool | Optional | n/a | Whether each returned message includes the User ID of its publisher in the `uuid` property. |
| decrypt | bool | Optional | `False` | Whether the SDK decrypts each message with the crypto module of the client. Without it, `message` holds the stored payload. If decryption fails, the item keeps the stored payload and sets `error`. The keyword argument of `fetch_messages()` is `decrypt_messages`, and the builder method is `decrypt_messages()`. |

### Returns

`fetch_messages()` returns an `Envelope` whose `result` is a `PNFetchMessagesResult` and whose `status` is a `PNStatus`.

#### PNFetchMessagesResult

| Property | Type | Description |
| --- | --- | --- |
| channels | dict | Maps each channel name to a list of [`PNFetchMessageItem`](#pnfetchmessageitem) objects, oldest first. |
| start_timetoken | int | The `start` value of the request, or `None` when the request set none. |
| end_timetoken | int | The `end` value of the request, or `None` when the request set none. |

#### PNFetchMessageItem

| Property | Type | Description |
| --- | --- | --- |
| message | any | The message payload. |
| timetoken | str | Timetoken that PubNub assigned to the message. |
| meta | any | Metadata that the publisher set at publish time, or `None` when the message has none. |
| uuid | str | User ID of the publisher. Present only when the response holds it, for example with `include_uuid`. |
| message_type | any | PubNub message type. Present only when the response holds it, for example with `include_message_type`. |
| actions | dict | Message actions on the message, grouped by action type and then by action value. Each action is a dict with `uuid` and `actionTimetoken`. An empty dict when the message has no actions. `None` without `include_message_actions`. |
| error | Exception | Decryption error, or `None`. Set only when the SDK fails to decrypt the message, and `message` then holds the stored payload. |

With `include_message_actions` set to `true`, PubNub truncates the response when the returned messages hold more than 25000 message actions in total. The Python result has no `more` property, so it does not report where the truncation stopped. Lower `count` to fetch fewer messages in each call.

### Examples

#### Syntax

```python
pubnub.fetch_messages() \
    .channels(channels: Union[str, List[str]]) \
    .count(count: int) \
    .start(start: int) \
    .end(end: int) \
    .include_meta(include_meta: bool) \
    .include_message_actions(include_message_actions: bool) \
    .include_message_type(include_message_type: bool) \
    .include_custom_message_type(include_custom_message_type: bool) \
    .include_uuid(include_uuid: bool) \
    .decrypt_messages(decrypt: bool) \
    .sync() -> PNFetchMessagesResultEnvelope
```

#### Basic usage

Retrieve the last message on a channel:

```python
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

pnconfig = PNConfiguration()
pnconfig.subscribe_key = "my_subkey"
pnconfig.publish_key = "my_pubkey"
pnconfig.ssl = True
pnconfig.user_id = "my_custom_user_id"
pubnub = PubNub(pnconfig)
```

#### Basic usage (Builder Pattern)

```python
envelope = pubnub.fetch_messages() \
    .channels(["my_channel"]) \
    .maximum_per_channel(1) \
    .include_message_actions(True) \
    .include_meta(True) \
    .include_message_type(True) \
    .include_uuid(True) \
    .sync()

for message in envelope.result.channels["my_channel"]:
    print("Message: %s" % message.message)
    print("Meta: %s" % message.meta)
    print("Timetoken: %s" % message.timetoken)

    for action_type in message.actions:
        print("Message Action type: " + action_type)
```

#### Basic usage (Named Arguments)

```python
envelope = pubnub.fetch_messages(channels=["my_channel"], count=1, include_message_actions=True,
                                 include_meta=True, include_message_type=True, include_uuid=True).sync()

for message in envelope.result.channels["my_channel"]:
    print(f"Message: {message.message}")
    print(f"Meta: {message.meta}")
    print(f"Timetoken: {message.timetoken}")
```

#### Fetch messages in a time range

```python
envelope = pubnub.fetch_messages() \
    .channels(["my_channel"]) \
    .start(newer_timetoken) \
    .end(older_timetoken) \
    .sync()
```

#### Fetch messages from several channels

```python
envelope = pubnub.fetch_messages() \
    .channels(["ch1", "ch2"]) \
    .maximum_per_channel(30) \
    .sync()

for channel_name, items in envelope.result.channels.items():
    print(channel_name, len(items))
```

## Delete messages from history

This method requires that the Message Persistence add-on is [enabled](https://www.pubnub.com/docs/faq/getting-started.md#how-do-i-enable-an-add-on-feature-on-my-keyset) for your key in the [Admin Portal](https://admin.pubnub.com/). Related: [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md).

`delete_messages()` deletes stored messages from channel history, optionally within a time range, using a PubNub client for Python.

Delete-From-History must be enabled for the keyset in the Admin Portal before a delete call succeeds. A call on a keyset where it is off fails with a 403 error.

The `start` timetoken is always the exclusive boundary and the `end` timetoken is always the inclusive boundary. The call deletes the message at `end` but not the message at `start`, whichever of the two values is larger. For the full walkthrough, see [Delete messages from history](https://www.pubnub.com/docs/data-storage/message-history/delete-messages-from-history.md).

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | ID of the channel to delete messages from. An empty value fails validation with the message `Channel missing`. |
| start | int | Optional | n/a | Timetoken that sets the exclusive boundary of the range to delete. The call keeps the message at this timetoken. |
| end | int | Optional | n/a | Timetoken that sets the inclusive boundary of the range to delete. The call deletes the message at this timetoken. |

### Returns

The method returns an `Envelope`.

| Property | Type | Description |
| --- | --- | --- |
| result | dict | An empty dictionary. |
| status | PNStatus | The operation status. |

#### Delete a single message

To delete one message, pass its publish timetoken, which a successful `publish()` returns, as `end`. Pass the next higher or the next lower timetoken as `start`. For example, if `15526611838554310` is the publish timetoken, pass `15526611838554310` as `end` and either `15526611838554309` or `15526611838554311` as `start`. Both pairs delete only the message at `15526611838554310`.

### Examples

#### Syntax

```python
pubnub.delete_messages() \
    .channel(channel: str) \
    .start(start: int) \
    .end(end: int) \
    .sync() -> Envelope
```

#### Basic usage (Builder Pattern)

```python
envelope = pubnub.delete_messages() \
    .channel("my_channel") \
    .start(newer_timetoken) \
    .end(older_timetoken) \
    .sync()
```

#### Basic usage (Named Arguments)

```python
envelope = pubnub.delete_messages(channel="my_channel", start=tokens[3], end=tokens[2]).sync()
```

#### Delete a single message (Builder Pattern)

```python
envelope = pubnub.delete_messages() \
    .channel("my_channel") \
    .start(publish_timetoken - 1) \
    .end(publish_timetoken) \
    .sync()
```

#### Delete a single message (Named Arguments)

```python
envelope = pubnub.delete_messages(channel="my_channel", start=publish_timetoken - 1, end=publish_timetoken).sync()
```

## Message counts

This method requires that the Message Persistence add-on is [enabled](https://www.pubnub.com/docs/faq/getting-started.md#how-do-i-enable-an-add-on-feature-on-my-keyset) for your key in the [Admin Portal](https://admin.pubnub.com/). Related: [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md).

`message_counts()` returns the number of messages published to one or more channels since a timetoken, using a PubNub client for Python.

The count includes every message with a timetoken greater than the timetoken you pass for the channel, so a message at exactly that timetoken is not counted. On a keyset with Unlimited retention, `message_counts()` considers only messages published in the last 30 days.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str or list of str | Yes | n/a | IDs of the channels to count messages in. Pass a list of channel names or one string. A string is split on commas, so `"ch1,ch2"` names two channels. The keyword argument of `message_counts()` is `channels`. An empty value fails validation with the message `Channel missing`. |
| channel_timetokens | list of int or str | Yes | n/a | Timetokens from which to count messages, listed in the same order as `channel`. The list must hold exactly one timetoken per channel. Each item is an int or a str. The keyword argument of `message_counts()` is `channels_timetoken`. A list whose length differs from the number of channels fails validation with the message `The number of channels and the number of timetokens do not match.`. |

### Returns

`message_counts()` returns an `Envelope` whose `result` is a `PNMessageCountResult` and whose `status` is a `PNStatus`.

#### PNMessageCountResult

| Property | Type | Description |
| --- | --- | --- |
| channels | dict | Maps each channel name to its message count. A channel without messages has a count of `0`. A channel with 10,000 messages or more has a count of `10000`. |

### Examples

#### Syntax

```python
pubnub.message_counts() \
    .channel(channel: Union[str, List[str]]) \
    .channel_timetokens(channel_timetokens: List[Union[int, str]]) \
    .sync() -> PNMessageCountResultEnvelope
```

#### Basic usage (Builder Pattern)

```python
envelope = pubnub.message_counts() \
    .channel("my_channel") \
    .channel_timetokens([timetoken]) \
    .sync()
print(envelope.result.channels["my_channel"])
```

#### Basic usage (Named Arguments)

```python
envelope = pubnub.message_counts(channels="my_channel", channels_timetoken=[tokens[2]]).sync()
```

#### PNMessageCountResult

```json
{
  "channels": {
    "my_channel": 3
  }
}
```

#### Count messages with a different timetoken for each channel (Builder Pattern)

```python
envelope = pubnub.message_counts() \
    .channel(["my_channel", "my_channel_2"]) \
    .channel_timetokens([timetoken, other_timetoken]) \
    .sync()
print(envelope.result.channels)
```

#### Count messages with a different timetoken for each channel (Named Arguments)

```python
envelope = pubnub.message_counts(channels=["my_channel", "my_channel_2"],
                                 channels_timetoken=[tokens[1], other_timetoken]).sync()
```

## Not recommended history method

`history()` is a method of the PubNub Python SDK that fetches the messages of one channel. Its use is not recommended, and `fetch_messages()` replaces it.

The reference for apps that still call `history()` is [Message Persistence API: history() method that is not recommended for Python SDK](https://www.pubnub.com/docs/sdks/python/api-reference/message-persistence-legacy.md). New apps use [Fetch history](#fetch-history).

Last updated at: 2026-11-25T12:28:11.000Z
