---
source_url: https://www.pubnub.com/docs/sdks/asyncio/quickstart
title: "Quickstart: PubNub Python-Asyncio SDK"
updated_at: 2026-11-25T12:28:11.000Z
sdk_name: PubNub Python Asyncio SDK
sdk_version: 10.9.1
description: Send your first message with the PubNub Python-Asyncio SDK. Install it with pip, subscribe to a channel, publish, and see the message arrive.
---

# Quickstart: PubNub Python-Asyncio SDK

PubNub Python Asyncio 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

In this quickstart you write a "Hello, World" script. The script connects to PubNub, subscribes to a channel, and publishes a message that arrives in the same script. You need Python 3.9 or later and a single file.

For other install options, refer to [Set up your Python-Asyncio environment](https://www.pubnub.com/docs/sdks/asyncio/set-up-your-environment.md).

## Before you begin

You need a basic understanding of Python and asyncio, and a PubNub account.

### Get your PubNub keys

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
* Find your publish and subscribe keys in the app dashboard

When you create an app, PubNub generates a keyset. Use separate keysets for development and production.

## Install

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

Install the SDK with `pip`:

```bash
pip install pubnub
```

## Initialize

Create a Python script named `pubnub_asyncio_demo.py`. Create the `PubNubAsyncio` client inside an `async` function, so that it uses the running event loop. Replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

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

async def main():
    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'

    pubnub = PubNubAsyncio(pnconfig)
```

Set the `user_id` to identify the user or device that connects to PubNub, and keep it unchanged for the lifetime of that user or device. Without a `user_id`, you can't connect to PubNub.

See the [Configuration](https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration.md) section of the SDK documentation.

## Subscribe

Listeners let your app react to events and messages. This status listener prints each connection status change. It extends `SubscribeListener`, which also lets the script wait until the client is connected.

```python
class StatusListener(SubscribeListener):
    def status(self, pubnub, status):
        super().status(pubnub, status)
        print(f'Status: {status.category.name}')
```

Add the listener inside `main()`, below the client:

```python
    status_listener = StatusListener()
    pubnub.add_listener(status_listener)
```

To receive messages on a channel, subscribe to it. Create a subscription for the channel, set a message handler, and activate the subscription:

```python
    my_channel = 'example'
    subscription = pubnub.channel(my_channel).subscription()
    subscription.on_message = lambda message: print(f'Message received: {message.message}')
    subscription.subscribe()
    print(f'Subscribed to channel: {my_channel}')
```

See the [Subscribe](https://www.pubnub.com/docs/sdks/asyncio/api-reference/subscribe.md#subscribe) section of the SDK documentation.

## Publish

When you publish a message to a channel, PubNub delivers it to every subscriber of that channel. A message can be any JSON-serializable data smaller than 32 KiB, such as an object, array, integer, or string.

Wait until the client is connected, then publish. Wait a few seconds for the message to arrive, then call `await pubnub.stop()` to close the client before the script exits.

```python
    await status_listener.wait_for_connect()

    try:
        result = await pubnub.publish().channel(my_channel).message({'msg': 'Hello from PubNub Python-Asyncio SDK!'}).result()
        print(f'Published message with timetoken: {result.timetoken}')
    except PubNubException as e:
        print(f'Publish failed: {e}')

    await asyncio.sleep(3)
    await pubnub.stop()
    print('Cleanup complete.')
```

See the [Publish](https://www.pubnub.com/docs/sdks/asyncio/api-reference/publish.md#publish) section of the SDK documentation.

## Run

The script below combines the code from the previous steps and starts the event loop with `asyncio.run()`. Save it as `pubnub_asyncio_demo.py`, replace the demo keys, and run it from your terminal:

```bash
python pubnub_asyncio_demo.py
```

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

class StatusListener(SubscribeListener):
    def status(self, pubnub, status):
        super().status(pubnub, status)
        print(f'Status: {status.category.name}')

async def main():
    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'

    pubnub = PubNubAsyncio(pnconfig)

    status_listener = StatusListener()
    pubnub.add_listener(status_listener)

    my_channel = 'example'
    subscription = pubnub.channel(my_channel).subscription()
    subscription.on_message = lambda message: print(f'Message received: {message.message}')
    subscription.subscribe()
    print(f'Subscribed to channel: {my_channel}')

    await status_listener.wait_for_connect()

    try:
        result = await pubnub.publish().channel(my_channel).message({'msg': 'Hello from PubNub Python-Asyncio SDK!'}).result()
        print(f'Published message with timetoken: {result.timetoken}')
    except PubNubException as e:
        print(f'Publish failed: {e}')

    await asyncio.sleep(3)
    await pubnub.stop()
    print('Cleanup complete.')

if __name__ == '__main__':
    asyncio.run(main())
```

The script prints output similar to this:

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

You receive the message you published because the client subscribes to the same channel. The order of the `Published` and `Message received` lines can differ.

If the message does not arrive, see [Troubleshooting](https://www.pubnub.com/docs/sdks/asyncio/troubleshooting.md). If the script prints a 403 (Access Denied) error, your keyset may have Access Manager enabled. Check that your token has read permissions for the subscribed channel. See [Configure access control](https://www.pubnub.com/docs/security/access-control/configure-access-control.md).

## Next steps

You created your first PubNub Python-Asyncio application. Here is what to explore next:

* Build a feature with the [how-tos](https://www.pubnub.com/docs/sdks/asyncio.md), such as showing who is online or loading message history.
* Learn about the [Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk.md) for ready-to-use chat features such as typing indicators and read receipts.
* Try out [Presence](https://www.pubnub.com/docs/sdks/asyncio/api-reference/presence.md) to track online and offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/asyncio/api-reference/message-persistence.md) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/asyncio/api-reference/access-manager.md) to secure your channels.
* Explore [Channel Groups](https://www.pubnub.com/docs/sdks/asyncio/api-reference/channel-groups.md) to organize your channels.
* Explore the [GitHub repository](https://github.com/pubnub/python) for more code samples.
* Check the [SDK reference documentation](https://www.pubnub.com/docs/sdks/asyncio/api-reference/configuration.md) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) or ask the AI assistant (the magnifying glass icon at the top of the page).

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