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
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 310 Dec 14, 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
Cookiecutter API for creating Custom Skills for Azure Search using Python and Docker

cookiecutter-spacy-fastapi Python cookiecutter API for quick deployments of spaCy models with FastAPI Azure Search The API interface is compatible wit

Microsoft 379 Jan 03, 2023
FastAPI native extension, easy and simple JWT auth

fastapi-jwt FastAPI native extension, easy and simple JWT auth

Konstantin Chernyshev 19 Dec 12, 2022
This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

0 Sep 24, 2022
Toolkit for developing and maintaining ML models

modelkit Python framework for production ML systems. modelkit is a minimalist yet powerful MLOps library for Python, built for people who want to depl

140 Dec 27, 2022
Cbpa - Coinbase Pro Automation for buying your favourite cryptocurrencies

cbpa Coinbase Pro Automation for making buy orders from a default bank account.

Anthony Corletti 3 Nov 27, 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
FastAPI with async for generating QR codes and bolt11 for Lightning Addresses

sendsats An API for getting QR codes and Bolt11 Invoices from Lightning Addresses. Share anywhere; as a link for tips on a twitter profile, or via mes

Bitkarrot 12 Jan 07, 2023
REST API with FastAPI and JSON file.

FastAPI RESTAPI with a JSON py 3.10 First, to install all dependencies, in ./src/: python -m pip install -r requirements.txt Second, into the ./src/

Luis Quiñones Requelme 1 Dec 15, 2021
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
Keepalive - Discord Bot to keep threads from expiring

keepalive Discord Bot to keep threads from expiring Installation Create a new Di

Francesco Pierfederici 5 Mar 14, 2022
This project shows how to serve an ONNX-optimized image classification model as a web service with FastAPI, Docker, and Kubernetes.

Deploying ML models with FastAPI, Docker, and Kubernetes By: Sayak Paul and Chansung Park This project shows how to serve an ONNX-optimized image clas

Sayak Paul 104 Dec 23, 2022
Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks

Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks. It provides a fully self-contained docker image that is easy to orchestrate, m

Redowan Delowar 96 Jan 02, 2023
Easily integrate socket.io with your FastAPI app 🚀

fastapi-socketio Easly integrate socket.io with your FastAPI app. Installation Install this plugin using pip: $ pip install fastapi-socketio Usage To

Srdjan Stankovic 210 Dec 23, 2022
CLI and Streamlit applications to create APIs from Excel data files within seconds, using FastAPI

FastAPI-Wrapper CLI & APIness Streamlit App Arvindra Sehmi, Oxford Economics Ltd. | Website | LinkedIn (Updated: 21 April, 2021) fastapi-wrapper is mo

Arvindra 49 Dec 03, 2022
FastAPI Auth Starter Project

This is a template for FastAPI that comes with authentication preconfigured.

Oluwaseyifunmi Oyefeso 6 Nov 13, 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
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
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