Skip to main content

Socket.IO wrapper for FastApi applications

Project description

Fastapi-socketio-handler

FastAPI + Socket.IO integration made modular, extensible and simple.

A clean event-based wrapper that helps you organize your Socket.IO server logic using decorators, handlers, and namespaces.


🔧 Features

  • 📡 Socket.IO server for FastAPI apps
  • 🧩 Handler registration via decorators
  • 📁 Namespace-based routing
  • 🔁 Redis pub/sub support (scaling)
  • 💡 Typed, extensible, and testable architecture
  • 🧪 Ready for pytest & async testing

📦 Installation

pip install fastapi-socketio-handler

🚀 Quick Start

1. Define a handler

# app/chat_handler.py

from socketio_handler import BaseSocketHandler, register_handler


@register_handler(namespace="/chat")
class ChatSocketHandlers(BaseSocketHandler):

    def register_events(self):
        self.sio.on("typing", self.event_typing, namespace=self.namespace)
        self.sio.on("stop_typing", self.event_stop_typing, namespace=self.namespace)

    async def connect(self, sid: str, environ: dict, auth: dict = None):
        if not auth or "token" not in auth:
            return False  # Reject connection
        return True

    async def event_typing(self, sid: str, data: dict, *args):
        print(f'Typing event from {sid}: {data}', args)

    async def event_stop_typing(self, sid: str, data: dict, *args):
        print(f'StopTyping event from {sid}: {data}', args)

2. Use with lifespan (recommended)

# core/db.py
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine

engine = create_async_engine(url="database_uri", echo=True)
async_session = async_sessionmaker(bind=engine, expire_on_commit=False, autocommit=False, autoflush=False)
# core/lifespan.py
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING

from socketio_handler import SocketManager

from .db import async_session

import app.chat_handler  # 👈 force-import handlers to trigger decorator registration

if TYPE_CHECKING:
    from fastapi import FastAPI
    
@asynccontextmanager
async def lifespan(app: "FastAPI"):
    """
    Lifespan context manager for FastAPI application.
    Useful for initializing and cleaning up resources.
    """
    async with (
        SocketManager(
            redis_url="redis://localhost:6379",
            async_session=async_session,
        ) as socket_manager,
    ):
        socket_manager.mount_to_app(app)
        socket_manager.register_events()
        app.state.socket_manager = socket_manager
        yield
# main.py
from fastapi import FastAPI
from core.lifespan import lifespan

app = FastAPI(lifespan=lifespan)

3. Connect from frontend

const socket = io('http://localhost:8000/chat', {
  auth: {
    token: 'your-auth-token'
  }
});

socket.emit("typing", { chatId: "..." });

🧪 Testing

This package includes pytest-based test utilities.
You can run the tests with:

  • Install dependencies for testing
poetry install --with dev
  • Run tests
pytest

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_socketio_handler-0.2.0.tar.gz (5.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_socketio_handler-0.2.0-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_socketio_handler-0.2.0.tar.gz.

File metadata

  • Download URL: fastapi_socketio_handler-0.2.0.tar.gz
  • Upload date:
  • Size: 5.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.13.5 Linux/6.11.0-1018-azure

File hashes

Hashes for fastapi_socketio_handler-0.2.0.tar.gz
Algorithm Hash digest
SHA256 a08a385751304d13bef047cea03ed86142b381e854e474739ca128b8d3fbdd0d
MD5 6a31df1fc348a670b81728bf0e50d526
BLAKE2b-256 8186788fc273cfa18c6e66a32b934da8accd3842809515e6b9fa3b33bbe0826d

See more details on using hashes here.

File details

Details for the file fastapi_socketio_handler-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_socketio_handler-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 aeb036139b8c8a9f63f32562dab5f968f9eddfe3775feb0680b7a9fb729cf894
MD5 7853e3ea645f4b84471e88fe6a210f29
BLAKE2b-256 1cd2bfb94dfb43cc15d4d9cba70cad5b6a4809a5bb4addab3a81b82ea4111692

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page