---
source_url: https://www.pubnub.com/docs/sdks/asyncio
title: Python-Asyncio API & SDK Docs 10.6.3
updated_at: 2026-05-21T15:46:02.428Z
sdk_name: PubNub Python Asyncio SDK
---

> 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


# Python-Asyncio API & SDK Docs 10.6.3

PubNub Python Asyncio SDK

Install:

```bash
pip install pubnub
```

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide helps you get up and running with PubNub in your Python application using the asyncio application programming interface (API). The Python-Asyncio software development kit (SDK) provides a simple interface for integrating PubNub real-time messaging into asynchronous Python applications. Whether you build a web service, desktop application, or Internet of Things (IoT) device, this guide shows you how to get started.

## Prerequisites

Before we dive in, make sure you have:

* A basic understanding of Python and asyncio
* Python 3.9 or later installed
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create an app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

There are several ways to install the PubNub Python SDK:

#### Use pip

Install with `pip`:

```bash
pip install pubnub
```

#### Source code

Clone the [GitHub repository](https://github.com/pubnub/python):

```bash
git clone https://github.com/pubnub/python
```

View the [supported platforms](https://www.pubnub.com/docs/sdks/asyncio/platform-support) for more information about compatibility.

## Steps

### Initialize PubNub

Create a Python script with the following content. This is the minimum configuration required to send and receive messages with PubNub.

Replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

```python
# Import required modules
import asyncio
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio

# Set up PubNub configuration
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo'  # Replace with your subscribe key
pnconfig.publish_key = 'demo'    # Replace with your publish key
pnconfig.user_id = 'asyncio-user'

# Create a PubNub instance
pubnub = PubNubAsyncio(pnconfig)
```

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration) section of the SDK documentation.

### Set up event listeners

Listeners help the application react to events and messages. You can implement custom logic to respond to each type of message or event.

Use a status listener to handle connection status changes:

```python
from pubnub.pubnub_asyncio import SubscribeListener

# Create a custom listener for status events
class StatusListener(SubscribeListener):
    def status(self, pubnub, status):
        # This method is called when the status of the connection changes
        print(f'Status: {status.category.name}')
    
    # We're not implementing the message handler here as we'll use a subscription-specific handler

# Add the listener to your PubNub instance
status_listener = StatusListener()
pubnub.add_listener(status_listener)
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration#event-listeners) section of the SDK documentation.

### Create a subscription

To receive messages sent to a particular channel, you need to subscribe to it. You do this by creating a subscription and activating it:

```python
# Define the channel you want to subscribe to
my_channel = 'example'

# Create a subscription for the channel
subscription = pubnub.channel(my_channel).subscription()

# Set up a message handler
subscription.on_message = lambda message: print(f'Message received: {message.message}')

# Subscribe to the channel
subscription.subscribe()

print(f'Subscribed to channel: {my_channel}')
```

The SDK offers multiple ways to handle incoming messages. A subscription-specific handler (as shown above) is recommended for most applications.

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/asyncio/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

```python
import asyncio
from pubnub.exceptions import PubNubException

async def publish_message():
    # Wait for a moment to ensure the subscription is active
    await asyncio.sleep(1)
    
    # Create a message
    message = {
        'msg': 'Hello from PubNub Python-Asyncio SDK!'
    }
    
    try:
        # Publish using result() which directly returns the result (or raises an exception)
        result = await pubnub.publish().channel(my_channel).message(message).result()
        print(f'Published message with timetoken: {result.timetoken}')
    except PubNubException as e:
        print(f'Publish failed: {e}')

# Run the async function
asyncio.run(publish_message())
```

The Python-Asyncio SDK provides two ways to handle callbacks:

* Using `result()` which returns just the result and raises exceptions directly
* Using `future()` which returns an envelope with both result and status objects

### Run the app

To test the code, save it as `pubnub_asyncio_demo.py` and run it from your terminal:

```bash
python pubnub_asyncio_demo.py
```

When you run the application, you should see output similar to the following:

```text
Subscribed to channel: example
Status: PNConnectedCategory
Message received: {'msg': 'Hello from PubNub Python-Asyncio SDK!'}
Published message with timetoken: 16967543908123456
```

You receive the message that you published because the client subscribes to the same channel.

## Complete example

```python
import asyncio
from pubnub.exceptions import PubNubException
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub_asyncio import PubNubAsyncio, SubscribeListener

# Step 1: Initialize PubNub with configuration
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo'  # Replace with your subscribe key
pnconfig.publish_key = 'demo'    # Replace with your publish key
pnconfig.user_id = 'asyncio-user'
pnconfig.ssl = True              # Enable SSL for secure connection

pubnub = PubNubAsyncio(pnconfig)

# Step 2: Create a status listener
class StatusListener(SubscribeListener):
    def status(self, pubnub, status):
        print(f'Status: {status.category.name}')
    
    # We're only monitoring connection status, not messages

# Step 3: Add the listener
status_listener = StatusListener()
pubnub.add_listener(status_listener)

# Step 4: Define the channel and create a subscription
my_channel = 'example'
subscription = pubnub.channel(my_channel).subscription()

# Step 5: Set up a message handler for the subscription
subscription.on_message = lambda message: print(f'Message received: {message.message}')

# Step 6: Subscribe to the channel
subscription.subscribe()
print(f'Subscribed to channel: {my_channel}')

async def main():
    # Wait for connection to establish before publishing
    await asyncio.sleep(1)
    
    # Step 7: Create and publish a message
    message = {
        'msg': 'Hello from PubNub Python-Asyncio SDK!'
    }
    
    try:
        # Publish using result() which directly returns the result
        result = await pubnub.publish().channel(my_channel).message(message).result()
        print(f'Published message with timetoken: {result.timetoken}')
    except PubNubException as e:
        print(f'Publish failed: {e}')
    
    # Keep the script running to receive messages
    await asyncio.sleep(3)
    
    # Step 8: Clean up before exiting
    await pubnub.stop()
    print('Cleanup complete.')

# Run the async event loop
if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    except KeyboardInterrupt:
        print("Interrupted by user. Exiting...")
    finally:
        loop.close()
```

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct., Make sure you're not behind a firewall blocking PubNub's connections. |
| Message not received | Double-check that you're subscribed to the correct channel., Verify that the message was actually sent (check for any error messages)., Make sure you're waiting long enough for the message to be delivered. |
| Import errors | Ensure you've installed the PubNub package correctly., Check that you're using a compatible version of Python., Make sure all imports are correct. |

For more detailed troubleshooting information, refer to the [Troubleshooting](https://www.pubnub.com/docs/sdks/asyncio/troubleshoot) section of the SDK documentation.

## Next steps

Great job! 🎉 You've successfully created your first PubNub application with Python-Asyncio. Here are some exciting things you can explore next:

### Build chat

* Add [Channel Groups](https://www.pubnub.com/docs/sdks/asyncio/api-reference/channel-groups) to organize your channels.
* Implement typing indicators and read receipts.

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/asyncio/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/asyncio/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/asyncio/api-reference/access-manager) to secure your channels.

### Real examples

* Explore our [GitHub repository](https://github.com/pubnub/python/) for more code samples.
* Check out the Python SDK examples for practical examples.

### More help

* Check out the [SDK reference documentation](https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.