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
Get MODBUS data from Sofar (K-TLX) inverter through LSW-3 or LSE module

SOFAR Inverter + LSW-3/LSE Small utility to read data from SOFAR K-TLX inverters through the Solarman (LSW-3/LSE) datalogger. Two scripts to get inver

58 Dec 29, 2022
Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI

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

ZeBrains Team 9 Nov 10, 2022
Fast, simple API for Apple firmwares.

Loyal Fast, Simple API for fetching Apple Firmwares. The API server is closed due to some reasons. Wait for v2 releases. Features Fetching Signed IPSW

11 Oct 28, 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 01, 2022
FastAPI pagination

FastAPI Pagination Installation # Basic version pip install fastapi-pagination # All available integrations pip install fastapi-pagination[all] Avail

Yurii Karabas 561 Jan 07, 2023
Asynchronous event dispatching/handling library for FastAPI and Starlette

fastapi-events An event dispatching/handling library for FastAPI, and Starlette. Features: straightforward API to emit events anywhere in your code ev

Melvin 238 Jan 07, 2023
MS Graph API authentication example with Fast API

MS Graph API authentication example with Fast API What it is & does This is a simple python service/webapp, using FastAPI with server side rendering,

Andrew Hart 4 Aug 11, 2022
Voucher FastAPI

Voucher-API Requirement Docker Installed on system Libraries Pandas Psycopg2 FastAPI PyArrow Pydantic Uvicorn How to run Download the repo on your sys

Hassan Munir 1 Jan 26, 2022
A kedro-plugin to serve Kedro Pipelines as API

General informations Software repository Latest release Total downloads Pypi Code health Branch Tests Coverage Links Documentation Deployment Activity

Yolan Honoré-Rougé 12 Jul 15, 2022
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 08, 2022
A minimum reproducible repository for embedding panel in FastAPI

FastAPI-Panel A minimum reproducible repository for embedding panel in FastAPI Follow either This Tutorial or These steps below ↓↓↓ Clone the reposito

Tyler Houssian 15 Sep 22, 2022
Cube-CRUD is a simple example of a REST API CRUD in a context of rubik's cube review service.

Cube-CRUD is a simple example of a REST API CRUD in a context of rubik's cube review service. It uses Sqlalchemy ORM to manage the connection and database operations.

Sebastian Andrade 1 Dec 11, 2021
API Simples com python utilizando a biblioteca FastApi

api-fastapi-python API Simples com python utilizando a biblioteca FastApi Para rodar esse script são necessárias duas bibliotecas: Fastapi: Comando de

Leonardo Grava 0 Apr 29, 2022
Lightning FastAPI

Lightning FastAPI Lightning FastAPI framework, provides boiler plates for FastAPI based on Django Framework Explaination / | │ manage.py │ README.

Rajesh Joshi 1 Oct 15, 2021
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
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
cookiecutter template for web API with python

Python project template for Web API with cookiecutter What's this This provides the project template including minimum test/lint/typechecking package

Hitoshi Manabe 4 Jan 28, 2021
Prometheus exporter for several chia node statistics

prometheus-chia-exporter Prometheus exporter for several chia node statistics It's assumed that the full node, the harvester and the wallet run on the

30 Sep 19, 2022
Pagination support for flask

flask-paginate Pagination support for flask framework (study from will_paginate). It supports several css frameworks. It requires Python2.6+ as string

Lix Xu 264 Nov 07, 2022
Generate Class & Decorators for your FastAPI project ✨🚀

Classes and Decorators to use FastAPI with class based routing. In particular this allows you to construct an instance of a class and have methods of that instance be route handlers for FastAPI & Pyt

Yasser Tahiri 34 Oct 27, 2022