Easily integrate socket.io with your FastAPI app 🚀

Overview

fastapi-socketio

PyPI Changelog License

Easly integrate socket.io with your FastAPI app.

Installation

Install this plugin using pip:

$ pip install fastapi-socketio

Usage

To add SocketIO support to FastAPI all you need to do is import SocketManager and pass it FastAPI object.

# app.py
from fastapi import FastAPI
from fastapi_socketio import SocketManager

app = FastAPI()
socket_manager = SocketManager(app=app)

Now you can use SocketIO directly from your FastAPI app object.

# socket_handlers.py
from .app import app

@app.sio.on('join')
async def handle_join(sid, *args, **kwargs):
    await app.sio.emit('lobby', 'User joined')

Or you can import SocketManager object that exposes most of the SocketIO functionality.

# socket_handlers2.py
from .app import socket_manager as sm

@sm.on('leave')
async def handle_leave(sid, *args, **kwargs):
    await sm.emit('lobby', 'User left')

Development

To contribute to this library, first checkout the code. Then create a new virtual environment:

cd fastapi-socketio
python -mvenv venv
source venv/bin/activate

Or if you are using pipenv:

pipenv shell

Now install the dependencies and tests:

pip install -e '.[test]'

To run the tests:

pytest

Run example

To run the examples simply run:

PYTHONPATH=. python examples/app.py

Before running example make sure you have all dependencies installed.

Contributors

For list of contributors please reefer to CONTRIBUTORS.md file in this repository.

Comments
  • Error: Get socket.io 404 error

    Error: Get socket.io 404 error

    I try to run the package but received this error:

    127.0.0.1:51474 - "GET /socket.io/?EIO=3&transport=polling&t=NOi5NZ- HTTP/1.1" 404 Not Found

    This is my code

    from fastapi import FastAPI
    from fastapi_socketio import SocketManager
    
    app = FastAPI()
    
    sio = SocketManager(app=app, cors_allowed_origins=["*"])
    
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    
    @sio.on('connect')
    async def connect():
        print('connect')
    
    if __name__ == '__main__':
        import logging
        import sys
    
        logging.basicConfig(level=logging.DEBUG,
                            stream=sys.stdout)
    
        import uvicorn
    
        uvicorn.run("main:app", host='127.0.0.1',
                    port=8000, reload=True, debug=False)
    
    opened by msyazwan 8
  • this is not even working at all

    this is not even working at all

    main.py

    from fastapi import FastAPI
    from fastapi_socketio import SocketManager
    
    app = FastAPI()
    socket_manager = SocketManager(app=app)
    
    
    @app.get("/")
    async def root():
        return {"message": "Hello World"}
    
    
    @app.sio.on('connect')
    async def handle_connect(sid, *args, **kwargs):
        await app.sio.emit('connect', 'User joined')
    

    CLIENT SIDE

    import {io} from 'socket.io-client';
    
    const socket =  io('ws://127.0.0.1:8000', {
          path: 'ws/socket.io',
          autoConnect: true
      })
    
      socket.on('connect', (data) => {
        console.log(data)
      })``` 
    opened by ahmetkca 5
  • PIP Installation Result in Empty/Incomplete Module

    PIP Installation Result in Empty/Incomplete Module

    The PIP command appears to work:

    $ pip install fastapi-socketio
    Collecting fastapi-socketio
      Downloading fastapi_socketio-0.1-py3-none-any.whl (6.0 kB)
    Installing collected packages: fastapi-socketio
    Successfully installed fastapi-socketio-0.1
    

    But the resulting module is effectively empty:

    $ find .../site-packages/fastapi_socketio/
    .../site-packages/fastapi_socketio/
    .../site-packages/fastapi_socketio/__pycache__
    .../site-packages/fastapi_socketio/__pycache__/__init__.cpython-38.pyc
    .../site-packages/fastapi_socketio/__init__.py
    

    The __init__py looks like a stub.

    $ cat .../site-packages/fastapi_socketio/__init__.py 
    def example_function():
        return 1 + 1
    
    opened by tolmanam 4
  • enter_room and leave_room don't work

    enter_room and leave_room don't work

    Hello! In https://github.com/pyropy/fastapi-socketio/pull/20 you added ability to join and leave rooms, but you made it as properties so when you call sio.enter_room(sid, room)

    it results to

    TypeError: enter_room() missing 2 required positional arguments: 'sid' and 'room'
    

    It should be not properties but methods.

    opened by Roxe322 2
  • Add **kwargs to SocketManager

    Add **kwargs to SocketManager

    Adds **kwargs to SocketManager constructor. These are simply passed to socketio.AsyncServer, as it supports a number of options not supported by SocketManager.

    This would also remove the need for issue #10 and its associated PR #29.

    opened by adamlwgriffiths 1
  • Adding CORS middleware and using SocketManager causes multiple values for Access-Control-Allow-Origin header

    Adding CORS middleware and using SocketManager causes multiple values for Access-Control-Allow-Origin header

    After adding both CORSMiddleware from FastApi and using SocketManager, which adds another CORS head, it results in the following error when trying to connect from the client:

    The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4200, http://localhost:4200', but only one is allowed.

    This is my fast api set up code:

    app = FastAPI()
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=['http://localhost:4200'],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    socket_manager = SocketManager(app=app, async_mode="asgi", cors_allowed_origins="*")
    

    The first CORS middleware access is so that the client can query the API but then the socketmanager also adds its own header.

    Any solutions / help would be much appreciated!

    opened by deanthing 1
  • Constant disconnect / reconnect

    Constant disconnect / reconnect

    Hi, I've got a pretty bare-bones FastAPI new project with fastapi-socketio, and socket.io-client. I set up a simple set-timeout to socket.emit() from the client, but it just disconnects / reconnects. I'lll see if I can show some code soon, but posting first in case there's a common known solution for this?

    image

    opened by lefnire 1
  • Too many package dependencies

    Too many package dependencies

    Hi there. I just noticed when using your module that a lot of modules got pulled in. In particular, the netifaces module is pulled in, which is a binary extension. And others. Browsing your code, I can't see that there are other direct dependencies than fastapi and python-socketio. But the Pipfile includes a host of extensions, and so does setup.py. (python-engineio is automatically added as part of python-socketio) Not sure why the module needs the various "extras" in setup.py, since there is no extras code.

    enhancement 
    opened by kristjanvalur 1
  • SocketManager: Add optional argument pass-through to socketio.AsyncServer constructor

    SocketManager: Add optional argument pass-through to socketio.AsyncServer constructor

    There are times when it may be necessary to be able to pass optional arguments to the AsyncServer constructor.

    The current SocketManager constructor passes a fixed set of arguments when it initializes the _sio instance.

    Perhaps an optional dict argument, socketio_server_args could be passed down into the AsyncServer constructor, as kwargs.

    I'll try to work up a PR for this soon.

    opened by inactivist 1
  • Use cors_allowed_origins in AsyncServer

    Use cors_allowed_origins in AsyncServer

    I needed CORS on my entire app, so I used app.add_middleware(CORSMiddleware, ...) with a specific origin. This broke websockets because it caused duplicate headers for requests to /ws/*:

    access-control-allow-origin: http://localhost:3000
    access-control-allow-credentials: true
    access-control-allow-credentials: true
    access-control-allow-origin: http://localhost:3000
    

    (For some reason this messed up Firefox's CORS verification) So, I tried to explicitly disabling it with cors_allowed_origins=[], but I realized the parameter wasn't being used. This PR fixes that. Note that I changed the default parameter to "*" so that the behavior would remain unchanged.

    opened by MatthewScholefield 1
  • Add allowed CORS origins support

    Add allowed CORS origins support

    Add allowed CORS origins support based upon current state of FastAPI app.

    If FastAPI app does have CORS middleware mounted set SocketManager allowed origins to empty list.

    Passing it empty list will make sure that app doesn't break.

    enhancement help wanted good first issue 
    opened by pyropy 1
  • 403 Forbidden - connection failed

    403 Forbidden - connection failed

    I am trying to run the example app. Only change is port number 8002 in my code. I see this error when I try to make a WebSocket request to the server from Postman

    Error: Unexpected server response: 403
    Handshake Details
    Request URL: http://localhost:8002/socket.io/?EIO=4&transport=websocket
    Request Method: GET
    Status Code: 403 Forbidden
    Request Headers
    Sec-WebSocket-Version: 13
    Sec-WebSocket-Key: fKVQf5eYrPb4tfZx6iHFEg==
    Connection: Upgrade
    Upgrade: websocket
    Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
    Host: localhost:8002
    Response Headers
    Date: Thu, 22 Dec 2022 04:43:26 GMT
    Content-Length: 0
    Content-Type: text/plain
    Connection: close
    

    How can this be fixed? Appreciate any pointers.

    opened by meerasndr 0
  • Mobile browser click events are not detected

    Mobile browser click events are not detected

    Hello,

    I am using FastAPI with socketIO and using socket emit(Javascript) for sending client button "onclick" event to server which listens to this event and then emits some data after calculation. This works perfectly fine on laptop browser, however when I tested upon mobile browser(Chrome), the button click does not work. I tested on mobile browser with a simple Javascript alert after removing the emit function and it works. So it appears like, the issue is with socket emit.

    Here is my Server Code:

    from fastapi import FastAPI, Request
    import json
    from fastapi_socketio import SocketManager
    import uvicorn
    import time
    import subprocess
    import asyncio
    from fastapi.templating import Jinja2Templates
    from fastapi.responses import HTMLResponse
    import socketio
    from fastapi.staticfiles import StaticFiles
    
    
    app = FastAPI()
    sio = socketio.AsyncServer(cors_allowed_origins='*', async_mode='asgi')
    socketio_app = socketio.ASGIApp(sio, app)
    templates = Jinja2Templates(directory="templates")
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    @sio.on('my_event')
    async def servermessage(data):
        data = asyncio.create_task(ssh())
        while True:
            if data.done():
                value = data.result()
                await sio.emit('response',"SSH Status:" + " " + value)
                break
            else:
                await sio.emit('response', "SSH Status:" + " " + "Please Wait..")
    
    
    
    async def ssh():
        cmd1 = 'systemctl status sshd| grep Active | awk -F " " \'{print$2}\''
        listing1 = subprocess.run(cmd1,stdout=subprocess.PIPE,shell=True,universal_newlines=True)
        result = listing1.stdout
        await asyncio.sleep(8)
        return result
    
    @app.get("/", response_class=HTMLResponse)
    async def main(request: Request):
        return templates.TemplateResponse("base.html", {"request":request})
    

    Here is my Javascript

    <script type="text/javascript" charset="utf-8">
    const socket = io("http://fastapi:8000");
    socket.on('connect', function (data) {
      console.log('Successfully connected!');
    });
    
    function myupdate(event) {
    	socket.emit("my_event", function(msg) {
           });
    }
    socket.on('response', function (data) {
    	if(data.includes("Please")) {
    		document.getElementById("sshimg").style.display="block";
    		document.getElementById("ssh").innerHTML=data;
    	} else {
    		document.getElementById("sshimg").style.display="none";
    		document.getElementById("ssh").innerHTML=data;
    	}
    
    });
    </script>
      </head>
      <body>
    <center>
    <h1 style="color:black;background-color:#33ACFF;padding:30px">Welcome to Websockets</h1>
    </center>
    <br>
    <button class="btn btn-info" id="button1" style="margin:5px" onClick="myupdate()">Check Services</button>
    	    <p id="ssh" style="font-weight:bold;"></p>
    	    <img id="sshimg" style="display:none;margin-left: auto;margin-right: auto;"  src="/static/Spinner.svg" alt="Trulli" width="70" height="70">
    </body>
    </html>
    
    
    opened by csharmatech 0
  • How it works with real example (with bigger project structure)?

    How it works with real example (with bigger project structure)?

    In my case, I have problem with import everything from main file (with fastapi app object). https://github.com/michaldev/problem-with-fastapi-import

    Access to the app object is not required for other libraries.

    opened by michaldev 2
  • add register_namespace property

    add register_namespace property

    opened by TomW1605 0
  • How to support/add JWT Authentication

    How to support/add JWT Authentication

    I am a newbie and trying to figure out authentication. Are there any guidelines on the same? I was able to add extra_headers on client side, but unable to find any way to get and validate headers on serverside for fastapi-socketio

    opened by iamjagan 0
Releases(0.0.9)
Owner
Srdjan Stankovic
Python developer. Interested in distributed systems and Elixir.
Srdjan Stankovic
Sample-fastapi - A sample app using Fastapi that you can deploy on App Platform

Getting Started We provide a sample app using Fastapi that you can deploy on App

Erhan BÜTE 2 Jan 17, 2022
FastAPI-Amis-Admin is a high-performance, efficient and easily extensible FastAPI admin framework. Inspired by django-admin, and has as many powerful functions as django-admin.

简体中文 | English 项目介绍 FastAPI-Amis-Admin fastapi-amis-admin是一个拥有高性能,高效率,易拓展的fastapi管理后台框架. 启发自Django-Admin,并且拥有不逊色于Django-Admin的强大功能. 源码 · 在线演示 · 文档 · 文

AmisAdmin 318 Dec 31, 2022
FastAPI Socket.io with first-class documentation using AsyncAPI

fastapi-sio Socket.io FastAPI integration library with first-class documentation using AsyncAPI The usage of the library is very familiar to the exper

Marián Hlaváč 9 Jan 2, 2023
Instrument your FastAPI app

Prometheus FastAPI Instrumentator A configurable and modular Prometheus Instrumentator for your FastAPI. Install prometheus-fastapi-instrumentator fro

Tim Schwenke 441 Jan 5, 2023
Instrument your FastAPI app

Prometheus FastAPI Instrumentator A configurable and modular Prometheus Instrumentator for your FastAPI. Install prometheus-fastapi-instrumentator fro

Tim Schwenke 55 Feb 17, 2021
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 3, 2023
:rocket: CLI tool for FastAPI. Generating new FastAPI projects & boilerplates made easy.

Project generator and manager for FastAPI. Source Code: View it on Github Features ?? Creates customizable project boilerplate. Creates customizable a

Yagiz Degirmenci 1k Jan 2, 2023
Simple FastAPI Example : Blog API using FastAPI : Beginner Friendly

fastapi_blog FastAPI : Simple Blog API with CRUD operation Steps to run the project: git clone https://github.com/mrAvi07/fastapi_blog.git cd fastapi-

Avinash Alanjkar 1 Oct 8, 2022
Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI

FastAPI Ariadne Example Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI - GitHub ###Запуск на локальном окру

ZeBrains Team 9 Nov 10, 2022
Flask-vs-FastAPI - Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks.

Flask-vs-FastAPI Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks. IntroductionIn Flask is a popular mic

Mithlesh Navlakhe 1 Jan 1, 2022
FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management

FastAPI Server-sided Session FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management.

DevGuyAhnaf 5 Dec 23, 2022
fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability

FastAPI2 Admin Introduction fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability. Now

Glib 14 Dec 5, 2022
Code Specialist 27 Oct 16, 2022
Fastapi-ml-template - Fastapi ml template with python

FastAPI ML Template Run Web API Local $ sh run.sh # poetry run uvicorn app.mai

Yuki Okuda 29 Nov 20, 2022
This code generator creates FastAPI app from an openapi file.

fastapi-code-generator This code generator creates FastAPI app from an openapi file. This project is an experimental phase. fastapi-code-generator use

Koudai Aono 632 Jan 5, 2023
FastAPI Skeleton App to serve machine learning models production-ready.

FastAPI Model Server Skeleton Serving machine learning models production-ready, fast, easy and secure powered by the great FastAPI by Sebastián Ramíre

null 268 Jan 1, 2023
A minimal Streamlit app showing how to launch and stop a FastAPI process on demand

Simple Streamlit + FastAPI Integration A minimal Streamlit app showing how to launch and stop a FastAPI process on demand. The FastAPI /run route simu

Arvindra 18 Jan 2, 2023
Learn to deploy a FastAPI application into production DigitalOcean App Platform

Learn to deploy a FastAPI application into production DigitalOcean App Platform. This is a microservice for our Try Django 3.2 project. The goal is to extract any and all text from images using a technique called OCR.

Coding For Entrepreneurs 59 Nov 29, 2022
Github timeline htmx based web app rewritten from Common Lisp to Python FastAPI

python-fastapi-github-timeline Rewrite of Common Lisp htmx app _cl-github-timeline into Python using FastAPI. This project tries to prove, that with h

Jan Vlčinský 4 Mar 25, 2022