Registry / azure / azure-messaging-webpubsubservice

azure-messaging-webpubsubservice

JSON →
library1.3.0pypypi✓ verified 22d ago

The Azure Web PubSub service client library for Python enables developers to build real-time web applications using WebSockets and the publish-subscribe pattern. It provides server-side APIs to manage WebSocket client connections, send messages to clients, groups, or specific users, and control permissions. The library is actively maintained as part of the Azure SDK for Python, with a rapid release cadence, and the current stable version is 1.3.0.

pip install azure-messaging-webpubsubservice
INSTALL
IMPORT
SIG · AZURE-MESSAGING-WE
A
azure-messaging-webpubsubservice
azurepythonv1.3.0
Install
2.5s avg
Import
426ms
Disk
23MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.3.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.454s · 24.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.5s · import 0.398s · 25MB
23MB installed
● package 23MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

WebPubSubServiceClient
from azure.messaging.webpubsubservice import WebPubSubServiceClient
WebPubSubServiceAsyncClient
from azure.messaging.webpubsubservice.aio import WebPubSubServiceClient
The async client is found in the `.aio` submodule and typically aliased for clarity, or used directly if you prefer the original name from `aio`.

This quickstart demonstrates how to instantiate `WebPubSubServiceClient` using a connection string from an environment variable and send a plain text message to all connected clients within a specified hub. Ensure `AZURE_WEBPUBSUB_CONNECTION_STRING` and `AZURE_WEBPUBSUB_HUB` environment variables are set for authentication and hub selection, respectively.

import os from azure.messaging.webpubsubservice import WebPubSubServiceClient # --- Authentication --- # Option 1: Connection string (recommended for quickstart/dev) # Set environment variable AZURE_WEBPUBSUB_CONNECTION_STRING connection_string = os.environ.get('AZURE_WEBPUBSUB_CONNECTION_STRING', 'Endpoint=https://<your-service>.webpubsub.azure.com;AccessKey=<your-access-key>;Version=1.0;') # Set environment variable AZURE_WEBPUBSUB_HUB hub_name = os.environ.get('AZURE_WEBPUBSUB_HUB', 'myHub') if not connection_string or 'Endpoint=' not in connection_string: print("Please set the AZURE_WEBPUBSUB_CONNECTION_STRING environment variable or provide a valid connection string.") exit(1) if not hub_name or hub_name == 'myHub': print("Please set the AZURE_WEBPUBSUB_HUB environment variable or provide a valid hub name.") exit(1) # Create a WebPubSubServiceClient instance service_client = WebPubSubServiceClient.from_connection_string(connection_string, hub=hub_name) # --- Send a message to all clients in the hub --- try: print(f"Sending 'Hello World' to all clients in hub '{hub_name}'...") response = service_client.send_to_all("Hello World", content_type='text/plain') print(f"Message sent. Response: {response}") # Example: Send a JSON message # response = service_client.send_to_all({'message': 'Hello from Python!', 'type': 'greeting'}, content_type='application/json') # print(f"JSON message sent. Response: {response}") except Exception as e: print(f"An error occurred: {e}")
Debug
Known issues
breakingSupport for Python 2.7 has officially ended as of January 1, 2022. Users on Python 2.7 will not receive updates and should migrate to Python 3.6+ (or preferably 3.8+ as per current PyPI requirements).
fix
Upgrade your Python environment to version 3.8 or higher.
affects: <=1.0.0b2
gotchaWhen using Azure Active Directory (AAD) for authentication with `DefaultAzureCredential`, you must install the `azure-identity` package separately (`pip install azure-identity`) and enable AAD authentication on your Azure Web PubSub resource. Direct use of connection strings is simpler for initial setup but less secure for production.
fix
Install `azure-identity` and configure AAD on your Web PubSub resource, or use connection string/access key for simpler authentication.
affects: All versions
gotchaThe SDK provides both synchronous (`WebPubSubServiceClient`) and asynchronous (`WebPubSubServiceAsyncClient` from `azure.messaging.webpubsubservice.aio`) clients. Mixing sync and async operations without proper `asyncio` context can lead to unexpected behavior or deadlocks. Choose the appropriate client for your application's concurrency model.
fix
For asynchronous applications, use `WebPubSubServiceAsyncClient` and ensure all calls are awaited within an `asyncio` event loop. For synchronous applications, stick to `WebPubSubServiceClient`.
affects: All versions
gotchaError handling for server-side issues will often involve `azure.core.exceptions.HttpResponseError` rather than client-side `ValidationError`. This means you need to catch these exceptions for robust error handling, especially for issues like malformed requests or service-side failures.
fix
Implement `try-except HttpResponseError` blocks around API calls to handle potential server-side validation or other HTTP errors.
affects: All versions
Errors
Common errors & fixes
ValueError: The value provided for the url part endpoint was incorrect, and resulted in an invalid url
This error typically occurs when the connection string used to initialize the `WebPubSubServiceClient` is malformed or contains incorrect characters, preventing the client from parsing the endpoint URL correctly.
fix
Ensure the connection string is copied exactly from the Azure portal (Web PubSub service -> Keys -> Primary Connection string) without any modifications or extra spaces.
401 unauthorised
This error indicates an authentication failure, meaning the client is not authorized to perform the requested operation, often due to an incorrect access key, an expired token, or insufficient permissions granted to the identity used.
fix
Verify that the connection string or API key is correct and has the necessary permissions (e.g., 'Web PubSub Service Owner'). If using AAD, ensure the service principal or managed identity has the 'Web PubSub Service Owner' role. Check for token expiration if generating client access tokens.
ModuleNotFoundError: No module named 'azure.messaging.webpubsubservice'
This error means the `azure-messaging-webpubsubservice` package is not installed in your Python environment or the environment where your application is running.
fix
Install the package using pip: `python -m pip install azure-messaging-webpubsubservice`. Ensure your deployment environment (e.g., Azure App Service) has the package installed, potentially by including it in `requirements.txt` and enabling remote builds.
HttpHandlerUnexpectedResponse with status code 404
This error from the Web PubSub service indicates that an event registered in your hub's settings (e.g., `connect`, `message`) failed to reach or receive a response from the configured upstream event handler URL, often because the URL is incorrect or the handler is not running or accessible.
fix
Check the configured upstream URL for your event handler in the Azure Web PubSub service settings to ensure it is correct and reachable. Verify that your upstream server or Azure Function handling the event is deployed, running, and correctly configured to respond to the event.
Resource provider(s): Microsoft.SignalRService is not registered for subscription
This Azure subscription-level error prevents the creation or management of Web PubSub resources because the necessary resource provider (`Microsoft.SignalRService` is the namespace for both SignalR and Web PubSub) has not been registered with your Azure subscription.
fix
Register the `Microsoft.SignalRService` resource provider for your Azure subscription. This can be done via the Azure portal (Subscriptions -> Resource providers -> Search for `Microsoft.SignalRService` -> Register) or using Azure CLI: `az provider register --namespace Microsoft.SignalRService`.
Upgrade
Version history
1.3.0latest on PyPI · released Jul 8, 2025
Audit
Dependencies
azure-identityoptionalRequired for Azure Active Directory (AAD) authentication using `DefaultAzureCredential` or other `TokenCredential` types.
Agent activity
30 hits · last 30 days
node
24
OpenAI (training)
1
Resources