---
source_url: https://www.pubnub.com/docs/sdks/python/api-reference/files
title: File Sharing API for Python SDK
updated_at: 2026-06-16T12:52:10.880Z
sdk_name: PubNub Python SDK
sdk_version: 10.7.1
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# File Sharing API for Python SDK

PubNub Python SDK, use the latest version: 10.7.1

Install:

```bash
pip install pubnub@10.7.1
```

You can upload and share files up to 5 MB on PubNub. Common uses include sharing images in chat apps and documents in healthcare.

When you upload a file to a `channel`, PubNub stores it with your key. Subscribers on that `channel` receive a file event with the file ID, file name, and an optional description.

:::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. 1pubnub.publish() \2 .channel("myChannel") \3 .message("Hello from PubNub Python SDK") \4 .sync()
* .pn_async(callback) returns None and passes the values of Envelope.result and Envelope.status to a callback you must define beforehand. 1def my_callback_function(result, status):2 print(f'TT: {result.timetoken}, status: {status.category.name}')3 4pubnub.publish() \5 .channel("myChannel") \6 .message("Hello from PubNub Python SDK") \7 .pn_async(my_callback_function)
:::

## Send file

Upload the file to a specified channel.

This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.

For the last messaging step, `send_file` internally calls the [publish_file_message](#publish-file-message) method to publish a message on the channel.

The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.

For details on the method that publishes the file message, see [Publish file message](#publish-file-message).

### Method(s)

```python
pubnub.send_file() \
    .channel(String) \
    .file_name(String) \
    .message(Dictionary) \
    .should_store(Boolean) \
    .ttl(Integer) \
    .file_object(Python Object File or bytes) \
    .meta(Dictionary) \
    .custom_message_type(String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | String | Yes |  | Channel for the file. |
| file_name | String | Yes |  | Name of the file to send. |
| message | Dictionary | Optional |  | Message to send along with the file to the specified `channel`. |
| should_store | Boolean | Optional | `True` | Whether to store the published `file message` in the `channel` history. |
| ttl | Integer | Optional |  | How long the message should be stored in the channel's storage. |
| file_object | bytes | Yes |  | Input stream with file content. |
| meta | Dictionary | Optional |  | Metadata object which can be used with the filtering ability. |
| custom_message_type | String | Optional |  | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |

:::warning Deprecated parameter
The `cipher_key` parameter in this method is deprecated. We recommend that you configure the [crypto module](https://www.pubnub.com/docs/sdks/python/api-reference/configuration#crypto_module) on your PubNub instance instead. If you pass `cipher_key` as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

###### Builder Pattern

```python
import os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from pubnub.exceptions import PubNubException

def send_file(pubnub: PubNub, file_path: str, channel: str):
    try:
        with open(file_path, 'rb') as sample_file:
            response = pubnub.send_file() \
                .channel(channel) \
                .file_name("sample.gif") \
                .message({"test_message": "test"}) \
                .file_object(sample_file) \
                .sync()
            print("File sent successfully. File ID:", response.result.file_id)

    except PubNubException as e:
        print(f"Error: {e}")
    except FileNotFoundError:
        print(f"File not found: {file_path}")

def main():
    # Configuration for PubNub instance
    pn_config = PNConfiguration()
    pn_config.subscribe_key = os.getenv('SUBSCRIBE_KEY', 'demo')
    pn_config.publish_key = os.getenv('PUBLISH_KEY', 'demo')
    pn_config.user_id = os.getenv('USER_ID', 'my_custom_user_id')

    # Initialize PubNub client
    pubnub = PubNub(pn_config)

    # Send file
    send_file(pubnub, 'path/to/sample.gif', 'my_channel')

if __name__ == "__main__":
    main()
```

###### Named Arguments

```python
import os
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from pubnub.exceptions import PubNubException

def send_file(pubnub: PubNub, file_path: str, channel: str):
    try:
        with open(file_path, 'rb') as sample_file:
            response = pubnub.send_file(
                channel=channel,
                file_name="sample.gif",
                file_object=sample_file,
                message="Hey, it's gif not jif",
                custom_message_type="file-message"
            ).sync()
            print("File sent successfully. File ID:", response.result.file_id)

    except PubNubException as e:
        print(f"Error: {e}")
    except FileNotFoundError:
        print(f"File not found: {file_path}")

def main():
    # Configuration for PubNub instance
    pn_config = PNConfiguration()
    pn_config.subscribe_key = os.getenv('SUBSCRIBE_KEY', 'demo')
    pn_config.publish_key = os.getenv('PUBLISH_KEY', 'demo')
    pn_config.user_id = os.getenv('USER_ID', 'my_custom_user_id')

    # Initialize PubNub client
    pubnub = PubNub(pn_config)

    # Send file
    send_file(pubnub, 'path/to/sample.gif', 'ch1')

if __name__ == "__main__":
    main()
```

### Returns

Returns an `Envelope`.

| Field | Type | Description |
| --- | --- | --- |
| result | [PNSendFileResult](#pnsendfileresult) | A detailed object containing the result of the operation. |
| status | `PNStatus` | A status object with additional information. |

#### PNSendFileResult

| Property Name | Type | Description |
| --- | --- | --- |
| `name` | String | Name of the uploaded file. |
| `file_id` | String | ID of the uploaded file. |
| `timestamp` | String | The timetoken at which the message was published. |

### Other examples

#### 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/general/push/ios) and [Android Push](https://www.pubnub.com/docs/general/push/android) 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

Retrieve a list of files uploaded to a `channel`.

### Method(s)

```python
pubnub.list_files() \
    .channel(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Channel to get the list of files. |
| `limit`Type: IntDefault: n/a | The number of elements to return. |
| `next`Type: StringDefault: n/a | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |

### Sample code

#### Builder Pattern

```python
    config.publish_key = os.environ.get('PUBNUB_PUBLISH_KEY', 'demo')
    config.subscribe_key = os.environ.get('PUBNUB_SUBSCRIBE_KEY', 'demo')
    config.user_id = 'example'
    return PubNub(config)
# snippet.end
```

#### Named Arguments

```python
file_list_response = pubnub.list_files(channel="ch1", limit=10, next="xyz...abc").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']}")
```

### Returns

Returns an `Envelope`.

| Field | Type | Description |
| --- | --- | --- |
| result | [PNGetFilesResult](#pngetfilesresult) | A detailed object containing the result of the operation. |
| status | `PNStatus` | A status object with additional information. |

#### PNGetFilesResult

| Property Name | Type | Description |
| --- | --- | --- |
| `next` | String | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |
| `count` | Int | Number of files returned. |
| `data` | List | `List` of channel files. |

`data` contains the following properties:

| Property Name | Type | Description |
| --- | --- | --- |
| `id` | Long | `Id` of the uploaded file. |
| `name` | String | `Name` of the upload file. |
| `size` | String | `Size` of the uploaded file. |
| `created` | String | Time of creation. |

## Get file URL

Generate a URL to download a file from the target `channel`.

### Method(s)

```python
pubnub.get_file_url() \
    .channel(String) \
    .file_id(String) \
    .file_name(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Name of `channel` to which the file has been uploaded. |
| `file_name` *Type: String | Name under which the uploaded file is stored. |
| `file_id` *Type: String | Unique identifier for the file, assigned during upload. |

### Sample code

#### Builder Pattern

```python
# snippet.uploading_files
def upload_file(pubnub: PubNub, channel: str, file_path: str) -> dict:
    """Upload a given file to PubNub.

    Args:
        - pubnub (PubNub): The PubNub instance.
```

#### Named Arguments

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

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

### Returns

Returns an `Envelope`.

| Field | Type | Description |
| --- | --- | --- |
| result | [PNGetFileDownloadURLResult](#pngetfiledownloadurlresult) | A detailed object containing the result of the operation. |
| status | `PNStatus` | A status object with additional information. |

#### PNGetFileDownloadURLResult

| Property Name | Type | Description |
| --- | --- | --- |
| `file_url` | String | `URL` to be used to download the requested file. |

## Download file

Download a file from the specified `channel`.

### Method(s)

```python
pubnub.download_file() \
    .channel(String) \
    .file_id(String) \
    .file_name(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Name of `channel` to which the file has been uploaded. |
| `file_name` *Type: String | Name under which the uploaded file is stored. |
| `file_id` *Type: String | Unique identifier for the file, assigned during upload. |

:::warning Deprecated parameter
The `cipher_key` parameter in this method is deprecated. We recommend that you configure the [crypto module](https://www.pubnub.com/docs/sdks/python/api-reference/configuration#crypto_module) on your PubNub instance instead. If you pass `cipher_key` as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
:::

### Sample code

#### Builder Pattern

```python
        - file_path (str): The path to the file to upload.
    Returns:
        - str: The file ID of the uploaded file.
    """
    with open(file_path, 'rb') as sample_file:
        response = pubnub.send_file() \
            .channel(channel) \
            .file_name("sample.gif") \
            .message({"test_message": "test"}) \
```

#### Named Arguments

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

fw = open(f"{os.getcwd()}/{file_data['name']}", 'wb')
fw.write(download_file.result.data)

print(f"File saved as {os.getcwd()}/{file_data['name']}")
```

### Returns

Returns an `Envelope`.

| Field | Type | Description |
| --- | --- | --- |
| result | [PNDownloadFileResult](#pndownloadfileresult) | A detailed object containing the result of the operation. |
| status | `PNStatus` | A status object with additional information. |

#### PNDownloadFileResult

| Property Name | Type | Description |
| --- | --- | --- |
| `data` | bytes | Python bytes object. |

## Delete file

Delete a file from the specified `channel`.

### Method(s)

```python
pubnub.delete_file() \
    .channel(String) \
    .file_id(String) \
    .file_name(String)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | The `channel` from which to delete the file. |
| `file_id` *Type: String | Unique identifier of the file to be deleted. |
| `file_name` *Type: String | Name of the file to be deleted. |

### Sample code

#### Builder Pattern

```python
            .sync()
        return response.result
# snippet.end
```

#### Named Arguments

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

print(f"File deleted")
```

### Returns

Returns an `Envelope`.

| Field | Type | Description |
| --- | --- | --- |
| result | [PNDeleteFileResult](#pndeletefileresult) | A detailed object containing the result of the operation. |
| status | `PNStatus` | A status object with additional information. |

#### PNDeleteFileResult

| Property Name | Type | Description |
| --- | --- | --- |
| `status` | Int | Returns a status code. |

## Publish file message

Publish the uploaded file message to a specified channel.

This method is called internally by [send_file](#send-file) as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.

This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.

You can call this method when `send_file` fails and returns the `status.operation === PNPublishFileMessageOperation` error. In that case, you can use the data from the `status` object to try again and use `publish_file_message` to manually resend a file message to a channel without repeating the upload step.

### Method(s)

```python
pubnub.publish_file_message() \
    .channel(String) \
    .meta(Dictionary) \
    .message(Dictionary) \
    .file_id(String) \
    .custom_message_type(String) \
    .file_name(String) \
    .should_store(Boolean) \
    .ttl(Integer)
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: n/a | Name of `channel` to publish file message. |
| `meta`Type: DictionaryDefault: n/a | Metadata object which can be used with the filtering ability. |
| `message`Type: DictionaryDefault: n/a | The payload. |
| `file_id` *Type: StringDefault: n/a | Unique identifier of the file. |
| `custom_message_type`Type: StringDefault: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes `-` and underscores `_` are allowed. The value cannot start with special characters or the string `pn_` or `pn-`. Examples: `text`, `action`, `poll`. |
| `file_name` *Type: StringDefault: n/a | Name of the file. |
| `should_store`Type: BooleanDefault: `True` | Whether to store this message in history. Set to `False` to not store it. By default, messages are stored according to the retention policy set on your key. |
| `ttl`Type: IntDefault: `0` | How long the message should be stored in the channel's history. If not specified, defaults to the key set's retention value. |

### Sample code

#### Builder Pattern

```python
# synchronous:
envelope = pubnub.publish_file_message() \
    .channel("test_channel") \
    .meta({"test": "test"}) \
    .message({"test_message": "test"}) \
    .custom_message_type("file-message") \
    .file_id("fileID") \
    .file_name("knights_of_ni.jpg") \
    .ttl(22) \
    .sync()

# multithreaded asynchronous:
def callback(response, status):
    pass

pubnub.publish_file_message() \
    .channel("test_channel") \
    .meta({"test": "test"}) \
    .message({"test_message": "test"}) \
    .custom_message_type("file-message") \
    .file_id("fileID") \
    .file_name("knights_of_ni.jpg") \
    .ttl(22) \
    .pn_async(callback)
```

#### Named Arguments

```python
envelope = pubnub.publish_file_message(channel="test_channel",
                                       message="Bring me a shrubbery",
                                       file_id="fileID",
                                       file_name="knights_of_ni.jpg",
                                       custom_message_type="file-message",
                                       meta={"nice": True, "expensive": False},
                                       ttl=22) \
    .sync()
```

### Returns

Returns an `Envelope`.

| Field | Type | Description |
| --- | --- | --- |
| result | [PNPublishFileMessageResult](#pnpublishfilemessageresult) | A detailed object containing the result of the operation. |
| status | `PNStatus` | A status object with additional information. |

#### PNPublishFileMessageResult

The `publish_file_message()` operation returns a `PNPublishFileMessageResult` which contains the following property:

| Property Name | Type | Description |
| --- | --- | --- |
| `timestamp` | String | The timetoken at which the message was published. |