ChanX: Type-Safe WebSocket Framework for Django and FastAPI

1 week ago 16

What My Project Does

ChanX is a batteries-included WebSocket framework that works with both Django Channels and FastAPI. It eliminates the boilerplate and repetitive patterns in WebSocket development by providing:

  • Automatic message routing using Pydantic discriminated unions - no more if-else chains
  • Type safety with full mypy/pyright support and runtime Pydantic validation
  • Auto-generated AsyncAPI 3.0 documentation - like OpenAPI/Swagger but for WebSockets
  • Channel layer integration for broadcasting messages across servers with Redis
  • Event system to trigger WebSocket messages from anywhere in your application (HTTP views, Celery tasks, management commands)
  • Built-in authentication with Django REST framework permissions support
  • Comprehensive testing utilities for both frameworks
  • Structured logging with automatic request/response tracing

The same decorator-based API works for both Django Channels and FastAPI:

from typing import Literal from chanx.messages.base import BaseMessage from chanx.core.decorators import ws_handler, channel from chanx.channels.websocket import AsyncJsonWebsocketConsumer # Django # from chanx.fast_channels.websocket import AsyncJsonWebsocketConsumer # FastAPI class ChatMessage(BaseMessage): action: Literal["chat"] = "chat" payload: str (name="chat") class ChatConsumer(AsyncJsonWebsocketConsumer): groups = ["chat_room"] async def handle_chat(self, msg: ChatMessage) -> None: await self.broadcast_message( ChatNotification(payload=NotificationPayload( message=msg.payload, timestamp=datetime.now() )) )

Target Audience

ChanX is designed for production use and is ideal for:

  • Teams building real-time features who want consistent patterns and reduced code review overhead
  • Django projects wanting to eliminate WebSocket boilerplate while maintaining REST API-like consistency
  • FastAPI projects needing robust WebSocket capabilities (ChanX brings Django Channels' channel layers, broadcasting, and group management to FastAPI)
  • Type-safety advocates who want comprehensive static type checking for WebSocket development
  • API-first teams who need automatic documentation generation

Built from years of real-world WebSocket development experience, ChanX provides battle-tested patterns used in production environments. It has:

  • Comprehensive test coverage with pytest
  • Full type checking with mypy and pyright
  • Complete documentation with high interrogate coverage
  • Active maintenance and support

Comparison

vs. Raw Django Channels:

  • ChanX adds automatic routing via decorators (vs. manual if-else chains)
  • Type-safe message validation with Pydantic (vs. manual dict checking)
  • Auto-generated AsyncAPI docs (vs. manual documentation)
  • Enforced patterns for team consistency

vs. Raw FastAPI WebSockets:

  • ChanX adds channel layers for broadcasting (FastAPI has none natively)
  • Group management for multi-user features
  • Event system to trigger messages from anywhere
  • Same decorator patterns as Django Channels

vs. Broadcaster:

  • ChanX provides full WebSocket consumer abstraction, not just pub/sub
  • Type-safe message handling with automatic routing
  • AsyncAPI documentation generation
  • Testing utilities included

vs. Socket.IO:

  • Native Python/ASGI implementation (no Node.js required)
  • Integrates directly with Django/FastAPI ecosystems
  • Type safety with Python type hints
  • Leverages existing Django Channels or FastAPI infrastructure

Detailed comparison: https://chanx.readthedocs.io/en/latest/comparison.html

Tutorials

I've created comprehensive hands-on tutorials for both frameworks:

Django Tutorial: https://chanx.readthedocs.io/en/latest/tutorial-django/prerequisites.html

  • Real-time chat with broadcasting
  • AI assistant with streaming responses
  • Notification system
  • Background tasks with WebSocket notifications
  • Complete integration tests

FastAPI Tutorial: https://chanx.readthedocs.io/en/latest/tutorial-fastapi/prerequisites.html

  • Echo WebSocket with system messages
  • Real-time chat rooms with channel layers
  • ARQ background jobs with WebSocket updates
  • Multi-layer architecture
  • Comprehensive testing

Both use Git repositories with checkpoints so you can start anywhere or compare implementations.

Installation

# For Django pip install "chanx[channels]" # For FastAPI pip install "chanx[fast_channels]"

Links

I'd love to hear feedback or answer questions about WebSocket development in Python.

submitted by /u/huygl99 to r/Python
[link] [comments]
Read Entire Article