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
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 05, 2023
A Sample App to Demonstrate React Native and FastAPI Integration

React Native - Service Integration with FastAPI Backend. A Sample App to Demonstrate React Native and FastAPI Integration UI Based on NativeBase toolk

YongKi Kim 4 Nov 17, 2022
Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker.

FastAPI + SQLModel + Alembic Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker. Want to learn how to build th

228 Jan 02, 2023
FastAPI application and service structure for a more maintainable codebase

Abstracting FastAPI Services See this article for more information: https://camillovisini.com/article/abstracting-fastapi-services/ Poetry poetry inst

Camillo Visini 309 Jan 04, 2023
SQLAlchemy Admin for Starlette/FastAPI

SQLAlchemy Admin for Starlette/FastAPI SQLAdmin is a flexible Admin interface for SQLAlchemy models. Main features include: SQLAlchemy sync/async engi

Amin Alaee 683 Jan 03, 2023
京东图片点击验证码识别

京东图片验证码识别 本项目是@yqchilde 大佬的 JDMemberCloseAccount 识别图形验证码(#45)思路验证,若你也有思路可以提交Issue和PR也可以在 @yqchilde 的 TG群 找到我 声明 本脚本只是为了学习研究使用 本脚本除了采集处理验证码图片没有其他任何功能,也

AntonVanke 37 Dec 22, 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
Local Telegram Bot With FastAPI & Ngrok

An easy local telegram bot server with python, fastapi and ngrok.

Ömer Faruk Özdemir 7 Dec 25, 2022
Ansible Inventory Plugin, created to get hosts from HTTP API.

ansible-ws-inventory-plugin Ansible Inventory Plugin, created to get hosts from HTTP API. Features: Database compatible with MongoDB and Filesystem (J

Carlos Neto 0 Feb 05, 2022
A FastAPI Middleware of joerick/pyinstrument to check your service performance.

fastapi_profiler A FastAPI Middleware of joerick/pyinstrument to check your service performance. 📣 Info A FastAPI Middleware of pyinstrument to check

LeoSun 107 Jan 05, 2023
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 04, 2023
An alternative implement of Imjad API | Imjad API 的开源替代

HibiAPI An alternative implement of Imjad API. Imjad API 的开源替代. 前言 由于Imjad API这是什么?使用人数过多, 致使调用超出限制, 所以本人希望提供一个开源替代来供社区进行自由的部署和使用, 从而减轻一部分该API的使用压力 优势

Mix Technology 450 Dec 29, 2022
🚢 Docker images and utilities to power your Python APIs and help you ship faster. With support for Uvicorn, Gunicorn, Starlette, and FastAPI.

🚢 inboard 🐳 Docker images and utilities to power your Python APIs and help you ship faster. Description This repository provides Docker images and a

Brendon Smith 112 Dec 30, 2022
Prometheus exporter for metrics from the MyAudi API

Prometheus Audi Exporter This Prometheus exporter exports metrics that it fetches from the MyAudi API. Usage Checkout submodules Install dependencies

Dieter Maes 7 Dec 19, 2022
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
FastAPI client generator

FastAPI-based API Client Generator Generate a mypy- and IDE-friendly API client from an OpenAPI spec. Sync and async interfaces are both available Com

David Montague 283 Jan 04, 2023
Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

Michael Freeborn 465 Jan 07, 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
REST API with FastAPI and PostgreSQL

REST API with FastAPI and PostgreSQL To have the same data in db: create table CLIENT_DATA (id SERIAL PRIMARY KEY, fullname VARCHAR(50) NOT NULL,email

Luis Quiñones Requelme 1 Nov 11, 2021