The main goal of SocketAPI is to provide an easy-to-use and flexible framework for building WebSocket APIs using Python. It leverages the power of Starlette for handling WebSocket connections and Pydantic for data validation and serialization. It uses a single multiplexed WebSocket connection, allowing clients to exchange different types of information through endpoint-like actions and channel subscriptions, defined similarly to routes in FastAPI. The framework is inspired by both FastAPI and Phoenix LiveView, combining familiar declarative endpoints with real-time, channel-oriented communication.
Installation
You can install SocketAPI using pip:
pip install socketapi
Simple example
Server
from socketapi import SocketAPI
app = SocketAPI()
# Define "add_numbers" action - endpoint for performing calculations
@app.action("add_numbers")
async def add_numbers(a: int, b: int) -> int:
return a + b
# Define "chat" channel - subscription for receiving messages
@app.channel("chat")
async def chat_channel(message: str = "Welcome"):
return {"message": message}
# Action that sends a message to all "chat" channel subscribers
@app.action("send_message")
async def send_message(message: str):
await chat_channel(message=message)
Run the server with any ASGI server (e.g., Uvicorn):
uvicorn main:app --reload
Client Usage
Connect to the WebSocket endpoint at ws://localhost:8000/ and exchange JSON messages.
Calling an action (request-response pattern)
Send:
{"type": "action", "channel": "add_numbers", "data": {"a": 5, "b": 3}}
Receive:
{"type": "action", "channel": "add_numbers", "status": "completed", "data": 8}
Subscribing to a channel (pub/sub pattern)
Send:
{"type": "subscribe", "channel": "chat"}
Receive confirmation:
{"type": "subscribed", "channel": "chat"}
Broadcasting to channel subscribers
Send:
{"type": "action", "channel": "send_message", "data": {"message": "Hello everyone!"}}
Receive confirmation:
{"type": "action", "channel": "send_message", "status": "completed"}
All subscribers receive:
{"type": "data", "channel": "chat", "data": {"message": "Hello everyone!"}}
How it works:
- Actions (
@app.action) - endpoint-like, request-response pattern. Client sends a request and receives a response. - Channels (
@app.channel) - pub/sub pattern. Client subscribes to a channel and automatically receives all data emitted to that channel. - Single WebSocket - all operations (actions, channels) work through a single WebSocket connection multiplexed via the
channelfield.
