---
source_url: https://www.pubnub.com/docs/sdks/python/api-reference/file-sharing
title: File Sharing 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 File Sharing methods: send_file(), list_files(), get_file_url(), download_file(), delete_file(), and publish_file_message(), with parameters, results, and sample code."
---

# File Sharing 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 uploads, lists, downloads, and deletes files on channels with [File Sharing](https://www.pubnub.com/docs/data-storage/files/overview.md), and `send_file()` publishes a file message that announces each upload.

File Sharing must be enabled for the keyset in the [Admin Portal](https://admin.pubnub.com/). A file can be up to 5 MB. When Access Manager (v2/v3) is enabled, file operations need channel permissions. For how File Sharing works, retention, and permissions, see [Files](https://www.pubnub.com/docs/data-storage/files/overview.md).

:::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)
   ```
:::

A failed request raises a `PubNubException` from `.sync()`. The methods `list_files()`, `get_file_url()`, and `delete_file()` accept their parameters as keyword arguments or through builder methods of the same name. The methods `send_file()`, `download_file()`, and `publish_file_message()` take no arguments, so set their parameters through builder methods.

## Send file

`send_file()` uploads a file to a channel through a PubNub client for Python, then publishes a file message that announces the upload.

`send_file()` requests an upload URL from PubNub, uploads the file to the storage service, and publishes the file message with the file ID and name. For the publish step, see [Publish file message](#publish-file-message).

Subscribers to the channel receive a file event with the file ID, the file name, and the optional message that came with the upload. The Python SDK does not deliver file events to listeners, so read the file message with `fetch_messages()` from Message Persistence instead.

To encrypt files, set `cipher_key` on `PNConfiguration`. The SDK then encrypts the file content with the configured crypto module, or with the legacy module if you set none. It also encrypts the file message, which holds `message`, the file ID, and the file name. The SDK sends `channel` and `meta` unencrypted.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | ID of the channel to upload the file to. A request without a channel fails validation with the message `Channel missing`. |
| file_name | str | Yes | n/a | Name of the file to upload, which PubNub stores it under. A request without a file name fails validation with the message `File name is missing.`. |
| file_object | Union[BinaryIO, bytes] | Yes | n/a | Content to upload, as a binary file object opened for reading or as `bytes`. A request without content fails validation with the message `File object is missing.`. |
| message | Any | Optional | n/a | Message that travels with the file, such as a caption. Subscribers receive it in the file event. |
| should_store | bool | Optional | `False` | Whether PubNub stores the file message in [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md). `true` stores it and `false` skips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sends `store=0`, so PubNub does not store the file message. |
| ttl | int | Optional | `0` | The number of hours that Message Persistence keeps the file message. When omitted, the SDK sends `0`, and the retention of the keyset applies. PubNub ignores this value when it does not store the message. |
| meta | Any | Optional | n/a | Metadata that PubNub attaches to the file message. Subscribers can use it in [message filters](https://www.pubnub.com/docs/pub-sub/subscribe/filter-received-messages.md). |
| custom_message_type | str | Optional | n/a | A business-specific label for the message, for example `text`, `action`, or `poll`. |

A custom message type accepted by the PubNub Publish, Signal, and File Sharing APIs must be a case-sensitive alphanumeric string of 3 to 50 characters. Dashes (`-`) and underscores (`_`) are allowed. The value cannot start with a special character or with the reserved prefixes `pn_` or `pn-`.

The deprecated `cipher_key` builder method is documented in [Deprecated cipher_key parameter](#deprecated-cipher_key-parameter).

:::warning Memory usage for large files
The SDK doesn't cap upload size. Your keyset's [file size limit](https://www.pubnub.com/docs/architecture/limits.md#file-sharing) is 5 MB by default and can differ. The method `send_file()` reads the entire file into memory to encrypt and upload it, so memory use grows with file size.
Enforce your keyset's configured limit in your own upload path before calling `send_file()`.
:::

### Returns

`send_file()` returns an `Envelope` whose `result` is a `PNSendFileResult` and whose `status` is a `PNStatus`.

#### PNSendFileResult

| Property | Type | Description |
| --- | --- | --- |
| name | str | Name of the uploaded file, as PubNub stores it. |
| file_id | str | ID of the uploaded file, which PubNub assigned at upload. |
| timestamp | str | Timetoken at which PubNub published the file message. |

### Examples for Send file

#### Syntax

```python
pubnub.send_file() \
    .channel(channel: str) \
    .file_name(file_name: str) \
    .file_object(file_object: Union[BinaryIO, bytes]) \
    .message(message: Any) \
    .should_store(should_store: bool) \
    .ttl(ttl: int) \
    .meta(meta: Any) \
    .custom_message_type(custom_message_type: str) \
    .sync() -> Envelope
```

#### Basic usage

The sample reads the file from `file_path`, the path of the file to upload.

```python
with open("sample.gif", "rb") as sample_file:
    response = pubnub.send_file() \
        .channel("ch1") \
        .file_name("sample.gif") \
        .message({"test_message": "test"}) \
        .should_store(True) \
        .file_object(sample_file) \
        .sync()
print("File sent successfully. File ID:", response.result.file_id)
```

#### Send file with a custom message type

```python
with open("sample.gif", "rb") as sample_file:
    response_2 = pubnub.send_file() \
        .channel("ch1") \
        .file_name("sample.gif") \
        .message("Hey, it's gif not jif") \
        .custom_message_type("file-message") \
        .should_store(True) \
        .file_object(sample_file) \
        .sync()
print("File sent successfully. File ID:", response_2.result.file_id)
```

#### Send file with push notification

:::tip Trigger push notifications when sharing files
To send mobile push notifications when sharing a file, include `pn_apns` (for iOS) and/or `pn_fcm` (for Android) payloads in the `message` parameter of the `send_file` method.
When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.
:::

```python
message = {
  "text": "Check out this file!",
  "pn_apns": {
      "aps": {
          "alert": {"title": "New File", "body": "A file was shared"}
      },
      "pn_push": [{
          "targets": [{"topic": "com.yourapp.bundleid", "environment": "production"}],
          "version": "v2"
      }]
  },
  "pn_fcm": {
      "notification": {"title": "New File", "body": "A file was shared"}
  }
}

with open("example.txt", "rb") as file_object:
  result = pubnub.send_file()       .channel("my-channel")       .file_name("example.txt")       .file_object(file_object)       .message(message)       .sync()
```

For more details on push notification payload structure, see the [iOS Push](https://www.pubnub.com/docs/integrations/mobile-push-notifications/send-push-notifications-ios.md) and [Android Push](https://www.pubnub.com/docs/integrations/mobile-push-notifications/send-push-notifications-android.md) documentation. To prevent the sender from receiving their own push notification, add their device token to `excluded_devices` in the `pn_push` targets.

## List channel files

`list_files()` returns the files that File Sharing stores for a channel, using a PubNub client for Python.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | ID of the channel to list the files of. A request without a channel fails validation with the message `Channel missing`. |
| limit | int | Optional | n/a | Number of files to return in one call. A single list-files call returns up to 100 files for a channel. |
| next | str | Optional | n/a | Token from the `next` value of the previous response, which continues the list where that response ended. |

### Returns

`list_files()` returns an `Envelope` whose `result` is a `PNGetFilesResult` and whose `status` is a `PNStatus`.

#### PNGetFilesResult

| Property | Type | Description |
| --- | --- | --- |
| data | list of dict | The files on the channel, one dict per file. |
| count | int | Number of files in this response. |
| next | str | Token for the next page, which you pass as `next` in the following call. |

Each dict in `data` holds these keys:

| Key | Type | Description |
| --- | --- | --- |
| `id` | str | ID of the file, which PubNub assigned at upload. |
| `name` | str | Name of the file, as PubNub stores it. |
| `size` | int | Size of the file in bytes. |
| `created` | str | Time at which PubNub stored the file, as an ISO 8601 string. |

### Examples for List channel files

#### Syntax

```python
pubnub.list_files(
    channel: str,
    *,
    limit: int = None,
    next: str = None
) -> ListFiles
```

#### Basic usage (Builder Pattern)

```python
file_list_response = pubnub.list_files().channel("ch1").sync()
print(f"Found {len(file_list_response.result.data)} files:")

for file_data in file_list_response.result.data:
    print(f"  {file_data['name']} with id: {file_data['id']}")
```

#### Basic usage (Named Arguments)

```python
page_1 = pubnub.list_files(channel="ch1", limit=1).sync()
page_2 = pubnub.list_files(channel="ch1", limit=1, next=page_1.result.next).sync()
```

## Get file URL

`get_file_url()` requests the download URL of a file on a channel from PubNub, using a PubNub client for Python.

The URL points to the file as PubNub stores it, so a file that the sender encrypted stays encrypted.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | ID of the channel that holds the file. A request without a channel fails validation with the message `Channel missing`. |
| file_name | str | Yes | n/a | Name of the file to build the URL for, as PubNub stores it. A request without a file name fails validation with the message `File name is missing.`. |
| file_id | str | Yes | n/a | ID of the file to build the URL for, which PubNub assigned at upload. A request without a file ID fails validation with the message `File id is missing.`. |

### Sample code

The sample reads `id` and `name` from `file_data`, an entry of the `data` list that `list_files()` returns.

### Returns

`get_file_url()` returns an `Envelope` whose `result` is a `PNGetFileDownloadURLResult` and whose `status` is a `PNStatus`.

#### PNGetFileDownloadURLResult

| Property | Type | Description |
| --- | --- | --- |
| file_url | str | URL from which to download the requested file. |

### Examples for Get file URL

#### Syntax

```python
pubnub.get_file_url(
    channel: str,
    file_name: str,
    file_id: str
) -> GetFileDownloadUrl
```

#### Basic usage (Builder Pattern)

```python
download_url = pubnub.get_file_url() \
    .channel("ch1") \
    .file_id(file_data['id']) \
    .file_name(file_data['name']) \
    .sync()

print(f'  Download url: {download_url.result.file_url}')
```

#### Basic usage (Named Arguments)

```python
download_url = pubnub.get_file_url(channel="ch1",
                                   file_id=file_data['id'],
                                   file_name=file_data['name']) \
    .sync()

print(f'  Download url: {download_url.result.file_url}')
```

## Download file

`download_file()` downloads a file from a channel through a PubNub client for Python.

With `cipher_key` set on `PNConfiguration`, the SDK decrypts the file content with the configured crypto module, or with the legacy module if you set none.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | ID of the channel to download the file from. A request without a channel fails validation with the message `Channel missing`. |
| file_name | str | Yes | n/a | Name of the file to download, as PubNub stores it. A request without a file name fails validation with the message `File name is missing.`. |
| file_id | str | Yes | n/a | ID of the file to download, which PubNub assigned at upload. A request without a file ID fails validation with the message `File id is missing.`. |

The deprecated `cipher_key` builder method is documented in [Deprecated cipher_key parameter](#deprecated-cipher_key-parameter).

### Returns

`download_file()` returns an `Envelope` whose `result` is a `PNDownloadFileResult` and whose `status` is a `PNStatus`.

#### PNDownloadFileResult

| Property | Type | Description |
| --- | --- | --- |
| data | bytes | Content of the downloaded file. |

### Examples for Download file

#### Syntax

```python
pubnub.download_file() \
    .channel(channel: str) \
    .file_name(file_name: str) \
    .file_id(file_id: str) \
    .sync() -> Envelope
```

#### Basic usage

The sample reads `id` and `name` from `file_data`, an entry of the `data` list that `list_files()` returns, and writes the file to `save_path`.

```python
download_file = pubnub.download_file() \
    .channel("ch1") \
    .file_id(file_data['id']) \
    .file_name(file_data['name']) \
    .sync()

save_path = file_data['name']
with open(save_path, 'wb') as fw:
    fw.write(download_file.result.data)

print(f"File saved as {save_path}")
```

## Delete file

`delete_file()` deletes a file from a channel through a PubNub client for Python.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | ID of the channel to delete the file from. A request without a channel fails validation with the message `Channel missing`. |
| file_name | str | Yes | n/a | Name of the file to delete, as PubNub stores it. A request without a file name fails validation with the message `File name is missing.`. |
| file_id | str | Yes | n/a | ID of the file to delete, which PubNub assigned at upload. A request without a file ID fails validation with the message `File id is missing.`. |

### Sample code

The sample reads `id` and `name` from `file_data`, an entry of the `data` list that `list_files()` returns.

### Returns

`delete_file()` returns an `Envelope` whose `result` is a `PNDeleteFileResult` and whose `status` is a `PNStatus`.

#### PNDeleteFileResult

| Property | Type | Description |
| --- | --- | --- |
| status | int | Status that PubNub returns for the deletion. The value `200` means success. |

### Examples for Delete file

#### Syntax

```python
pubnub.delete_file(
    channel: str,
    file_name: str,
    file_id: str
) -> DeleteFile
```

#### Basic usage (Builder Pattern)

```python
envelope = pubnub.delete_file() \
    .channel("ch1") \
    .file_id(file_data['id']) \
    .file_name(file_data['name']) \
    .sync()

print("File deleted")
```

#### Basic usage (Named Arguments)

```python
envelope = pubnub.delete_file(channel="ch1",
                              file_id=file_data['id'],
                              file_name=file_data['name']) \
    .sync()

print("File deleted")
```

## Publish file message

`publish_file_message()` publishes a file message for a file that PubNub already stores, using a PubNub client for Python.

The file message carries the file ID and the file name, which together identify the file for download. Call `publish_file_message()` when the upload succeeded but the publish step of `send_file()` failed, to publish the file message without uploading the file again.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | str | Yes | n/a | ID of the channel to publish the file message to. A request without a channel fails validation with the message `Channel missing`. |
| file_id | str | Yes | n/a | ID of the uploaded file, which PubNub assigned at upload. A request without a file ID fails validation with the message `File id is missing.`. |
| file_name | str | Yes | n/a | Name of the uploaded file, as PubNub stores it. A request without a file name fails validation with the message `File name is missing.`. |
| message | Any | Optional | n/a | Message to publish with the file. Subscribers receive it in the file event. |
| should_store | bool | Optional | `False` | Whether PubNub stores the file message in [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md). `true` stores it and `false` skips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sends `store=0`, so PubNub does not store the file message. |
| ttl | int | Optional | `0` | The number of hours that Message Persistence keeps the file message. When omitted, the SDK sends `0`, and the retention of the keyset applies. PubNub ignores this value when it does not store the message. |
| meta | Any | Optional | n/a | Metadata that PubNub attaches to the file message. Subscribers can use it in [message filters](https://www.pubnub.com/docs/pub-sub/subscribe/filter-received-messages.md). |
| custom_message_type | str | Optional | n/a | A business-specific label for the file message, for example `text`, `action`, or `poll`. |

The deprecated `cipher_key` builder method is documented in [Deprecated cipher_key parameter](#deprecated-cipher_key-parameter).

### Returns

`publish_file_message()` returns an `Envelope` whose `result` is a `PNPublishFileMessageResult` and whose `status` is a `PNStatus`.

#### PNPublishFileMessageResult

| Property | Type | Description |
| --- | --- | --- |
| timestamp | str | Timetoken at which PubNub published the file message. |

### Examples for Publish file message

#### Syntax

```python
pubnub.publish_file_message() \
    .channel(channel: str) \
    .file_id(file_id: str) \
    .file_name(file_name: str) \
    .message(message: Any) \
    .should_store(should_store: bool) \
    .ttl(ttl: int) \
    .meta(meta: Any) \
    .custom_message_type(custom_message_type: str) \
    .sync() -> Envelope
```

#### Basic usage

The sample reads `file_id` and `file_name` from the result of an earlier `send_file()` call.

```python
envelope = pubnub.publish_file_message() \
    .channel("ch1") \
    .meta({"test": "test"}) \
    .message({"test_message": "test"}) \
    .custom_message_type("file-message") \
    .file_id(file_id) \
    .file_name(file_name) \
    .should_store(True) \
    .ttl(22) \
    .sync()
```

#### Publish a file message with a callback

```python
def callback(response, status):
    results.append((response, status))

pubnub.publish_file_message() \
    .channel("ch1") \
    .message("Bring me a shrubbery") \
    .file_id(file_id) \
    .file_name(file_name) \
    .should_store(True) \
    .pn_async(callback)
```

## Deprecated cipher_key parameter

The `cipher_key` builder method of `send_file()`, `publish_file_message()`, and `download_file()` is deprecated in the PubNub Python SDK and issues a warning. The cipher key in the client configuration replaces it.

The reference for apps that still call `cipher_key`, with the replacement, is [File Sharing API: deprecated cipher_key parameter for Python SDK](https://www.pubnub.com/docs/sdks/python/api-reference/file-sharing-legacy.md). New apps set `cipher_key` on `PNConfiguration` and, to use 256-bit AES-CBC, a [`crypto_module`](https://www.pubnub.com/docs/sdks/python/api-reference/configuration.md#crypto_module).

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