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
Formatting of dates and times in Flask templates using moment.js.

Flask-Moment This extension enhances Jinja2 templates with formatting of dates and times using moment.js. Quick Start Step 1: Initialize the extension

Miguel Grinberg 358 Nov 28, 2022
Keycloak integration for Python FastAPI

FastAPI Keycloak Integration Documentation Introduction Welcome to fastapi-keycloak. This projects goal is to ease the integration of Keycloak (OpenID

Code Specialist 113 Dec 31, 2022
An extension library for FastAPI framework

FastLab An extension library for FastAPI framework Features Logging Models Utils Routers Installation use pip to install the package: pip install fast

Tezign Lab 10 Jul 11, 2022
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python Examples. The beyonic APIs Doc Reference: https://apidocs.beyonic.com/ To start using the Beyonic API Python API, you need to start

Harun Mbaabu Mwenda 46 Sep 01, 2022
Single Page App with Flask and Vue.js

Developing a Single Page App with FastAPI and Vue.js Want to learn how to build this? Check out the post. Want to use this project? Build the images a

91 Jan 05, 2023
Light, Flexible and Extensible ASGI API framework

Starlite Starlite is a light and flexible ASGI API framework. Using Starlette and pydantic as foundations. Check out the Starlite documentation 📚 Cor

1.5k Jan 04, 2023
Hyperlinks for pydantic models

Hyperlinks for pydantic models In a typical web application relationships between resources are modeled by primary and foreign keys in a database (int

Jaakko Moisio 10 Apr 18, 2022
FastAPI + PeeWee = <3

FastAPIwee FastAPI + PeeWee = 3 Using Python = 3.6 🐍 Installation pip install FastAPIwee 🎉 Documentation Documentation can be found here: https://

16 Aug 30, 2022
A Python framework to build Slack apps in a flash with the latest platform features.

Bolt for Python A Python framework to build Slack apps in a flash with the latest platform features. Read the getting started guide and look at our co

SlackAPI 684 Jan 09, 2023
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
Practice-python is a simple Fast api project for dealing with modern rest api technologies.

Practice Python Practice-python is a simple Fast api project for dealing with modern rest api technologies. Deployment with docker Go to the project r

0 Sep 19, 2022
Simple example of FastAPI + Celery + Triton for benchmarking

You can see the previous work from: https://github.com/Curt-Park/producer-consumer-fastapi-celery https://github.com/Curt-Park/triton-inference-server

Jinwoo Park (Curt) 37 Dec 29, 2022
Opinionated set of utilities on top of FastAPI

FastAPI Contrib Opinionated set of utilities on top of FastAPI Free software: MIT license Documentation: https://fastapi-contrib.readthedocs.io. Featu

identix.one 543 Jan 05, 2023
Slack webhooks API served by FastAPI

Slackers Slack webhooks API served by FastAPI What is Slackers Slackers is a FastAPI implementation to handle Slack interactions and events. It serves

Niels van Huijstee 68 Jan 05, 2023
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 871 Dec 25, 2022
Twitter API monitor with fastAPI + MongoDB

Twitter API monitor with fastAPI + MongoDB You need to have a file .env with the following variables: DB_URL="mongodb+srv://mongodb_path" DB_URL2=

Leonardo Ferreira 3 Apr 08, 2022
Fastapi performans monitoring

Fastapi-performans-monitoring This project is a simple performance monitoring for FastAPI. License This project is licensed under the terms of the MIT

bilal alpaslan 11 Dec 31, 2022
FastAPI interesting concepts.

fastapi_related_stuffs FastAPI interesting concepts. FastAPI version :- 0.70 Python3 version :- 3.9.x Steps Test Django Like settings export FASTAPI_S

Mohd Mujtaba 3 Feb 06, 2022
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.

Full Stack FastAPI and PostgreSQL - Base Project Generator Generate a backend and frontend stack using Python, including interactive API documentation

Sebastián Ramírez 10.8k Jan 08, 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

268 Jan 01, 2023