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):

    async def on_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 on_typing(self, sid: str, data: dict, *args):
        print(f'Typing event from {sid}: {data}', args)

    async def on_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_handlers()
        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.4.0.tar.gz (5.4 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.4.0-py3-none-any.whl (6.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_socketio_handler-0.4.0.tar.gz
  • Upload date:
  • Size: 5.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.0 CPython/3.13.7 Linux/6.11.0-1018-azure

File hashes

Hashes for fastapi_socketio_handler-0.4.0.tar.gz
Algorithm Hash digest
SHA256 7c8bf6659ea9c4dee27381cc9c2864d48b10f8faa28324525f7a500018f603ed
MD5 4b895617eaf00bb7be048cda530cf146
BLAKE2b-256 26b5ec025b254af98074e2c30063a2e885ea063ab9b52c70487e3d39981f1033

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for fastapi_socketio_handler-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f7761f0d3c790e0c70ac9080b60242807cc502af1a094e23a161c1de8be69d67
MD5 43bc8f204eb774f991b5d9d8ac84e6e0
BLAKE2b-256 985cdd1eee8596121953b99734dfe51469a1c373d660e76043eeff99684b4750

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