Registry / http-networking / httpx-ws

httpx-ws

JSON →
library0.9.0pypypi✓ verified 24d ago

httpx-ws is a Python library that adds WebSocket client capabilities to the popular HTTPX library. It provides both synchronous and asynchronous APIs for connecting to WebSocket servers and sending/receiving messages, seamlessly integrating with HTTPX's client infrastructure. Currently at version 0.9.0, it maintains an active release cycle with frequent updates and improvements.

pip install httpx-ws
INSTALL
IMPORT
SIG · HTTPX-WS
H
httpx-ws
http-networkingpythonv0.9.0
Install
2.1s avg
Import
419ms
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.9.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.354s · 22.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.1s · import 0.316s · 23MB
20MB installed
● package 20MB
Code
Verified usage

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

WebSocketClient
from httpx_ws import WebSocketClient
Recommended class-based client API introduced in v0.8.0.
aconnect_ws
from httpx_ws import aconnect_ws
Older function-based async connection API; the class-based client is now preferred.
connect_ws
from httpx_ws import connect_ws
Older function-based sync connection API; the class-based client is now preferred.
WebSocketDisconnect
from httpx_ws import WebSocketDisconnect

Demonstrates connecting to a WebSocket server using the class-based `WebSocketClient`, sending text, and receiving text. It includes robust error handling for `WebSocketDisconnect` and `ExceptionGroup` (for v0.9.0+). Replace `ws://localhost:8000/ws` with your target WebSocket endpoint. Requires an active WebSocket server running at the specified URL to execute successfully.

import httpx from httpx_ws import WebSocketClient, WebSocketDisconnect import asyncio async def main(): # Connect to a local test WebSocket server (e.g., uvicorn with websockets) # For a real application, replace with your actual WebSocket URL websocket_url = "ws://localhost:8000/ws" try: async with httpx.AsyncClient() as client: async with WebSocketClient(websocket_url, client) as websocket: print(f"Connected to {websocket_url}") await websocket.send_text("Hello, WebSocket!") print("Sent: Hello, WebSocket!") # Try to receive a response, with a timeout try: data = await asyncio.wait_for(websocket.receive_text(), timeout=5.0) print(f"Received: {data}") except asyncio.TimeoutError: print("No data received within 5 seconds.") except* WebSocketDisconnect as e: print(f"WebSocket disconnected gracefully: {e}") except ExceptionGroup as eg: # Handle other exceptions wrapped in ExceptionGroup (v0.9.0+) # This ensures all potential wrapped errors are considered print(f"An ExceptionGroup occurred: {eg}") for exc in eg.exceptions: if isinstance(exc, WebSocketDisconnect): print(f"Caught WebSocketDisconnect within ExceptionGroup: {exc}") else: print(f"Caught other exception within ExceptionGroup: {exc}") raise exc # Re-raise if not specifically handled except Exception as e: print(f"An unexpected error occurred: {e}") if __name__ == "__main__": asyncio.run(main())
Debug
Known issues
breakingAsync exceptions, including `WebSocketDisconnect`, are now wrapped in `ExceptionGroup` when propagating out of the `async with` block for `WebSocketClient` (or `aconnect_ws`).
fix
Update `try...except` blocks to use the `except*` syntax for specific sub-exceptions (e.g., `except* WebSocketDisconnect`) or catch `ExceptionGroup` and iterate its `exceptions` attribute.
affects: 0.9.0+
breakingPython 3.9 support was dropped in v0.8.0, and Python 3.8 support was dropped in v0.7.0. The library now requires Python 3.10 or newer.
fix
Ensure your project is running on Python 3.10 or a newer compatible version.
affects: 0.7.0, 0.8.0, 0.9.0+
gotchaA new class-based API, `WebSocketClient`, was introduced in v0.8.0 and is now the recommended way to open WebSocket connections, replacing the older `connect_ws`/`aconnect_ws` functions.
fix
Migrate from `connect_ws`/`aconnect_ws` functions to `WebSocketClient` for new code and consider refactoring existing code to use the more flexible class-based approach (e.g., `async with httpx.AsyncClient() as client: async with WebSocketClient(url, client) as ws:`).
affects: 0.8.0+
breakingThe `subprotocol` parameter was removed from `AsyncWebSocketSession` and `WebSocketSession` constructors. Subprotocols are now automatically set from response headers.
fix
If you were directly instantiating `AsyncWebSocketSession` or `WebSocketSession` and passing `subprotocol`, remove this parameter. If using `connect_ws`/`aconnect_ws` or `WebSocketClient`, this change is typically transparent.
affects: 0.6.0+
Errors
Common errors & fixes
AttributeError: 'ASGIWebSocketTransport' object has no attribute '_task_group'
This error typically occurs when an `httpx.AsyncClient` used with `httpx-ws`'s `aconnect_ws` is not properly managed within an `async with` context manager, especially in testing scenarios with `FastAPI` and `pytest` fixtures.
fix
Ensure the `httpx.AsyncClient` is instantiated and used within an `async with` block, allowing its internal resources (like the `_task_group`) to be correctly initialized and managed.
TypeError: 'function' object is not subscriptable (related to anyio.create_memory_object_stream)
This error arises when `httpx-ws` is used with an outdated version of `anyio` (e.g., `anyio==3.7.1`), where `anyio.create_memory_object_stream` was not yet generic and thus not subscriptable.
fix
Upgrade `anyio` to a compatible version (e.g., `anyio>=3.8.0`) as `httpx-ws` relies on features from newer `anyio` versions.
httpx.StreamClosed: Attempted to read or stream content, but the stream has been closed.
This occurs when attempting to read the content of a `httpx.Response` object (specifically within a `WebSocketUpgradeError`) after the underlying HTTPX stream has already been closed, often due to the `WebSocketUpgradeError` propagating and closing the client's stream context manager.
fix
To reliably read the response content from a `WebSocketUpgradeError`, ensure you access and read the response body immediately upon catching the `WebSocketUpgradeError` before the surrounding `httpx.AsyncClient` or `aconnect_ws` context exits and closes the stream.
httpx_ws.WebSocketDisconnect: The server closed the websocket.
This exception is raised when the WebSocket connection is closed by the server. A common close code like 1006 ('Abnormal Closure') indicates the connection was terminated without a clean WebSocket closing handshake, often due to network issues, a server crash, or an invalid protocol use during the initial HTTP upgrade (before the WebSocket is fully established).
fix
Debug the server-side application to understand why it's closing the connection, check network stability, and ensure the client is sending valid WebSocket frames and adhering to the server's expected protocols. For client-side debugging, inspect server logs for errors and ensure the URL and subprotocols are correct.
httpx_ws.WebSocketUpgradeError: Unexpected response code: XXX
This error indicates that the initial HTTP handshake to upgrade the connection to the WebSocket protocol failed, often due to the server returning an unexpected HTTP status code (e.g., 400 Bad Request, 403 Forbidden, 500 Internal Server Error) instead of the expected 101 Switching Protocols.
fix
Check the WebSocket URL, ensure the server is running and configured to handle WebSocket connections correctly, verify any authentication or authorization mechanisms, and review the server's logs for the reason it denied the upgrade.
Upgrade
Version history
0.9.0latest on PyPI · released Mar 28, 2026
Audit
Dependencies
httpxrequiredCore HTTP client library that httpx-ws extends for WebSocket support.
anyiorequiredAsynchronous backend for concurrent operations and stream handling.
Agent activity
11 hits · last 30 days
node
10
Resources
httpx-ws — pip install httpx-ws · libregistry