Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Azure Web PubSub Chat service client library for Python

Azure Web PubSub chat is a managed chat capability built on Azure Web PubSub. It provides purpose-built client and server APIs for chat scenarios. Applications use the SDKs to communicate with the Azure service and work with chat-native concepts such as rooms, messages, members, and users. The service handles real-time message delivery and ordering, fan-out across a user's devices and browser tabs, room membership, and message persistence and retrieval.

Use this client library in an application server to:

  • Create and manage chat roles and permissions.
  • Create users, rooms, and room memberships.
  • List rooms, users, and the rooms associated with a user.
  • Create, list, update, and soft delete room topics.
  • Get room conversations and query persisted message history.
  • Update and delete persisted messages.
  • Generate client access credentials for Chat WebSocket clients.

Source code | Package (PyPI) | API reference documentation | Product documentation | Examples | Changelog

Getting started

Prerequisites

1. Install the package

python -m pip install azure-messaging-webpubsubchatservice

To use Microsoft Entra ID authentication, also install azure-identity:

python -m pip install azure-identity

2. Create and authenticate a WebPubSubChatServiceClient

The client supports a connection string, an AzureKeyCredential, or a Microsoft Entra ID token credential. The hub passed to the client must have Chat enabled.

Use a connection string

Get the connection string from the Azure portal or Azure CLI, and store it securely. See Web PubSub authorization for details.

import os
from azure.messaging.webpubsubchatservice import WebPubSubChatServiceClient

hub = os.environ.get("WPS_CHAT_HUB", "test_hub")
with WebPubSubChatServiceClient.from_connection_string(
    os.environ["WPS_CHAT_CONNECTION_STRING"], hub
) as connection_string_client:
    print(type(connection_string_client).__name__)

Use an access key

import os
from azure.core.credentials import AzureKeyCredential
from azure.messaging.webpubsubchatservice import WebPubSubChatServiceClient

endpoint = os.environ["WPS_CHAT_ENDPOINT"]
hub = os.environ.get("WPS_CHAT_HUB", "test_hub")
with WebPubSubChatServiceClient(
    endpoint,
    hub,
    AzureKeyCredential(os.environ["WPS_CHAT_ACCESS_KEY"]),
) as key_client:
    print(type(key_client).__name__)

Use Microsoft Entra ID

For recommended passwordless authentication, assign an appropriate Web PubSub data-plane role to the principal and use a credential from the Azure Identity library. The following example uses DefaultAzureCredential:

import os
from azure.identity import DefaultAzureCredential
from azure.messaging.webpubsubchatservice import WebPubSubChatServiceClient

endpoint = os.environ["WPS_CHAT_ENDPOINT"]
hub = os.environ.get("WPS_CHAT_HUB", "test_hub")
with WebPubSubChatServiceClient(endpoint, hub, DefaultAzureCredential()) as entra_client:
    print(type(entra_client).__name__)

For more information, see Authenticate Azure-hosted Python applications and Microsoft Entra authorization for Azure Web PubSub.

Key concepts

Hub

A hub is a logical collection of WebSocket connections. A chat hub adds built-in rooms, member management, message persistence, and chat-specific APIs.

This SDK applies only to chat hubs. Chat must be enabled on the target hub before the SDK can manage roles, users, rooms, members, conversations, or messages.

Role and permission

A role is a named collection of Chat permissions. User role names start with user., and room role names start with room.. Do not combine user and room permissions in one role.

User roles control operations such as creating rooms. Room roles control what a member can do in a particular room, such as publishing messages or reading message history.

User

A user represents an identity participating in chat, such as a human end user or an application. Client access credentials associate WebSocket connections with a user ID.

Room

A room groups users together and is the primary organizational unit for chat interactions. Every room has an automatically created default conversation.

Room member

A room member represents a user added to a room. Membership controls which users can receive and send messages in the room. In the service API, each room member is assigned a room role.

Conversation and message history

A conversation is an ordered message stream within a room. Every room has a default conversation, and additional named conversations can be created through topics.

Messages sent to a conversation are delivered in real time to the room's connected members. The chat service manages ordering and persistence, allowing members to load message history after reconnecting or joining later. The service client can list, update, and delete persisted messages.

ChatConversation.room_id identifies the room containing the conversation. list_messages returns messages from latest to earliest, using message IDs as pagination cursors. The returned pager follows the service's nextLink automatically. To resume a page iteration, pass its continuation token to by_page(continuation_token=...), not to list_messages itself.

Topic

A topic represents a named conversation within a room. Topics can be created, renamed, archived, and soft deleted independently of the room's default conversation.

Examples

The async snippet uses a client from azure.messaging.webpubsubchatservice.aio. Replace placeholders such as <room-id> with your application's resource identifiers.

Request-body styles

You can supply a JSON request body in three ways:

  • Model-based: use classes from azure.messaging.webpubsubchatservice.models with Python-style attributes and SDK-managed serialization.
  • Typed dictionary: use the TypedDict definitions from azure.messaging.webpubsubchatservice.types for static checking of dictionaries that use JSON field names.
  • Plain dictionary: pass a dictionary using JSON field names.

Model-based usage is recommended for getting started and is used throughout the examples below. Dictionaries are useful when your application already works with JSON-shaped data. All three styles call the same client methods; typed dictionaries are ordinary dictionaries at runtime and do not add runtime validation. See the examples guide for a comparison and examples of each style.

Explore the examples:

Generate client access credentials

Generate credentials that a Chat WebSocket client can use to connect as a specific user:

access = client.get_client_access_token(user_id="sample-user")
# Give access["url"] to the intended client to connect; it includes the access token.
# Print only the token-free base URL here. Do not log access["url"].
print(access["baseUrl"])

The returned URL contains an access token. Send it only to the intended client, and do not log or persist it in production.

Create a role

Create operations use dedicated request models such as ChatRoleCreateOrReplace and ChatRoomCreateOrReplace. PATCH operations use ChatTopicUpdate and ChatMessageUpdate, whose fields can be omitted to leave existing values unchanged. The operations return resource models such as ChatRole, ChatRoom, and ChatTopic, which include service-assigned identifiers and ETags.

Use the ChatRoleCreateOrReplace model and ChatPermission enum instead of a dictionary with permission string literals.

from azure.messaging.webpubsubchatservice.models import ChatPermission, ChatRoleCreateOrReplace

role = client.create_or_replace_role(
    "user.example",
    ChatRoleCreateOrReplace(permissions=[ChatPermission.USER_CREATE_ROOM]),
)
print(role.name, role.permissions)

See the synchronous role example and asynchronous role example for runnable model-and-enum examples. The selected role is created or replaced and remains in the hub; these examples do not create users or rooms.

List roles

for role in client.list_roles():
    print(role.name)

Create a user

The user role user.room_creator must already exist.

from azure.messaging.webpubsubchatservice.models import HumanChatUserCreateOrReplace

user = client.create_or_replace_user(
    "alice",
    HumanChatUserCreateOrReplace(nickname="Alice", role_name="user.room_creator"),
)
print(user.id, user.nickname)

Create a room

from azure.messaging.webpubsubchatservice.models import ChatRoomCreateOrReplace

room = client.create_or_replace_room("general", ChatRoomCreateOrReplace(title="General"))
print(room.id, room.default_conversation)

Add a room member

The room general, user alice, and room role room.contributor must already exist.

from azure.messaging.webpubsubchatservice.models import ChatRoomMemberCreateOrReplace

member = client.create_or_replace_room_member(
    "general",
    "alice",
    ChatRoomMemberCreateOrReplace(role_name="room.contributor"),
)
print(member.user_id, member.role_name)

List persisted messages

Replace <conversation-id> with an existing conversation ID.

for message in client.list_messages("<conversation-id>"):
    print(message.id, message.created_by, message.content.text)

Manage room topics

Replace <room-id> with an existing room ID and <topic-id> with the topic ID.

Create a topic

ChatTopicCreateOrReplace requires a title. When replacing an existing topic, you can also supply state, for example ChatTopicCreateOrReplace(title="Announcements", state=ChatTopicState.ARCHIVED). Import ChatTopicState from azure.messaging.webpubsubchatservice.models. Omit state when creating a topic.

from azure.messaging.webpubsubchatservice.models import ChatTopicCreateOrReplace

topic = client.create_or_replace_topic(
    "<room-id>",
    "<topic-id>",
    ChatTopicCreateOrReplace(title="Announcements"),
)
print(topic.id, topic.etag)

List topics

for topic in client.list_topics("<room-id>", max_page_size=10):
    print(topic.id, topic.title, topic.conversation_id)

Get a topic

topic = client.get_topic("<room-id>", "<topic-id>")
print(topic.id, topic.title, topic.state, topic.etag)

Archive a topic

Replace <topic-etag> with the ETag returned by a previous create or get operation, preserving its quotes. The update below changes only state; the existing title is left unchanged. To change only the title, use ChatTopicUpdate(title="New title").

from azure.core import MatchConditions
from azure.messaging.webpubsubchatservice.models import ChatTopicUpdate, ChatTopicState

topic = client.update_topic(
    "<room-id>",
    "<topic-id>",
    ChatTopicUpdate(state=ChatTopicState.ARCHIVED),
    etag='"<topic-etag>"',
    match_condition=MatchConditions.IfNotModified,
)
print(topic.id, topic.state, topic.etag)

Soft delete a topic

Replace <topic-etag> with the current ETag, including any change from an update.

from azure.core import MatchConditions

client.delete_topic(
    "<room-id>",
    "<topic-id>",
    etag='"<topic-etag>"',
    match_condition=MatchConditions.IfNotModified,
)

Use the topic's conversation_id with get_conversation and list_messages.

For conditional updates and deletes, pass the current ETag with MatchConditions.IfNotModified. A stale ETag prevents overwriting a topic that another caller has changed. Deleting a topic is a soft delete.

For individual API calls, see the operation examples.

List rooms and users

List rooms

for room in client.list_rooms(max_page_size=10):
    print(room.id, room.title)

List users

for user in client.list_users(max_page_size=10):
    print(user.id, user.kind)

List rooms for a user

Replace <user-id> with an existing user ID.

for room in client.list_rooms_for_user("<user-id>"):
    print(room.id, room.title)

For basic list calls, see the functions in the README snippet sources. Listing rooms for a user requires an existing user ID.

Collection iterators automatically fetch subsequent pages.

Use the asynchronous client

Run this snippet inside an async function with an authenticated async client; see the asynchronous client access example for the complete program.

access = await client.get_client_access_token(user_id="sample-user")
# Give access["url"] to the intended client to connect; it includes the access token.
# Print only the token-free base URL here. Do not log access["url"].
print(access["baseUrl"])

Run the examples

Set WPS_CHAT_CONNECTION_STRING and optionally WPS_CHAT_HUB (default: test_hub). The role examples use user.example; replace it with a role name reserved for the example. An existing role with that name is replaced. Install aiohttp to run async examples.

From the package directory, run, for example:

python samples/sample_roles_and_permissions.py
python samples/sample_roles_and_permissions_async.py

Troubleshooting

Handle service errors

Service operations raise HttpResponseError or a more specific subclass when a request fails:

The service error example reads an existing role, prints the status on failure, and re-raises the error. Replace user.example with the role name to read.

from azure.core.exceptions import HttpResponseError

try:
    role = client.get_role("user.example")
    print(role.name, role.permissions)
except HttpResponseError as error:
    print(f"Chat service request failed with status {error.status_code}")
    raise

Logging

This library uses the standard Python logging library. Enable HTTP logging for a client by passing logging_enable=True:

import logging
import os
import sys

from azure.identity import DefaultAzureCredential
from azure.messaging.webpubsubchatservice import WebPubSubChatServiceClient

logger = logging.getLogger("azure")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(stream=sys.stdout))

with DefaultAzureCredential() as credential:
    with WebPubSubChatServiceClient(
        os.environ["WPS_CHAT_ENDPOINT"],
        os.environ.get("WPS_CHAT_HUB", "test_hub"),
        credential,
        logging_enable=True,
    ) as client:
        print(type(client).__name__)

HTTP logs can contain sensitive information. Do not enable detailed logging in production without reviewing how logs are collected and protected. For more information, see Configure logging in the Azure SDK for Python.

Next steps

Explore the README snippet sources and complete package examples to learn how to:

  • Authenticate with a connection string, access key, or Microsoft Entra ID.
  • Manage roles, permissions, users, rooms, and room members.
  • Generate client access credentials.
  • Query, update, and delete message history.
  • Manage topic lifecycles and iterate over room and user collections.
  • Use synchronous and asynchronous clients.

See also the request-body style comparison.

Additional resources

Contributing

This project welcomes contributions and suggestions. See the contributing guide for instructions on building, testing, and submitting changes.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with questions or comments.

Release History

1.0.0b2 (2026-11-13)

Features Added

  • Added topic lifecycle operations (create or replace, list, get, update, and soft delete). Creation or replacement accepts ChatTopicCreateOrReplace, which requires title and accepts optional state for replacement; updates accept ChatTopicUpdate, whose fields are optional.
  • Added room, user, and user-room collection operations

Other Changes

  • Changed the default service API version from 2026-02-01-preview to 2026-08-01-preview for both existing and newly added Chat operations
  • Clarified that message IDs are pagination cursors for list_messages. The pager follows the service's nextLink; resume with by_page(continuation_token=...).

Breaking Changes

  • Renamed request-body parameters from resource to role, room, member, user, topic, or message, matching the operation's resource. Positional calls are unchanged.
  • Renamed ChatConversation.parent_room to room_id. The JSON field remains parentRoom.
  • Removed the continuation_token_parameter argument from listing operations. Resume paging with by_page(continuation_token=...) on the returned ItemPaged or AsyncItemPaged instead.
  • Create or replace operations now accept dedicated ChatRoleCreateOrReplace, ChatRoomCreateOrReplace, ChatRoomMemberCreateOrReplace, and ChatUserCreateOrReplace (including HumanChatUserCreateOrReplace) request models instead of resource response models.
  • Message updates accept ChatMessageUpdate, whose fields are optional, instead of ChatMessage. Resource response model names are unchanged.

1.0.0b1 (2026-10-08)

Features Added

  • Initial preview release of the Azure Web PubSub Chat Service client library for Python
  • Added connection string, access key, and Microsoft Entra ID authentication
  • Added client access token generation for connected Chat clients
  • Added built-in Chat role and permission constants
  • Support for room management (create, get, update, delete rooms)
  • Support for user management (create, get, delete users)
  • Support for room membership management (add, list, delete room members)
  • Support for message operations (list, update, delete messages)
  • Support for role-based access control (create, get, list, delete roles)

Metadata

Release files for azure-messaging-webpubsubchatservice 1.0.0b2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for azure-messaging-webpubsubchatservice 1.0.0b2
File Size Uploaded Provenance Actions
azure_messaging_webpubsubchatservice-1.0.0b2.tar.gz 104.1 kB Without provenance Details for azure_messaging_webpubsubchatservice-1.0.0b2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for azure-messaging-webpubsubchatservice 1.0.0b2
File Interpreter ABI Platform Actions
azure_messaging_webpubsubchatservice-1.0.0b2-py3-none-any.whl Python 3 none any Details for azure_messaging_webpubsubchatservice-1.0.0b2-py3-none-any.whl

Total release size: 189.7 kB

Release files / azure_messaging_webpubsubchatservice-1.0.0b2.tar.gz

Download URL azure_messaging_webpubsubchatservice-1.0.0b2.tar.gz
Size 104.1 kB
Tags Source
SHA-256 checksum
How to use checksums
17eb8b0f07bb4407f05e006b0d69df7d8cfc443415fa4a5a0e8452fda8c4b7aa
BLAKE2b-256 checksum
How to use checksums
41e509ae9b559382c4ea8383abc473277653b5d788b69e98e3ce45916bea2ecb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0

Release files / azure_messaging_webpubsubchatservice-1.0.0b2-py3-none-any.whl

Download URL azure_messaging_webpubsubchatservice-1.0.0b2-py3-none-any.whl
Size 85.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
27be303ff49d693f9fc11ecb9e26ddd76528145c52dad19a91ac370a8ead17b0
BLAKE2b-256 checksum
How to use checksums
f46cbe0790f6cb61acc82b410d380e37fbcfdc71cf427a23c6813bccd19d378a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0

Security for azure-messaging-webpubsubchatservice 1.0.0b2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page