Creating a WebSocket with FastAPI
Thanks to Starlette, FastAPI has built-in support to serve WebSockets. As we'll see, defining a WebSocket endpoint is quick and easy, and we'll be able to get started in minutes. However, things will get more complex as we try to add more features to our endpoint logic. Let's start simple, with a WebSocket that waits for messages and simply echoes them back.
In the following example, you'll see the implementation of such a simple case:
app.py
from fastapi import FastAPI, WebSocket from starlette.websockets import WebSocketDisconnect app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() try: while True: data = await websocket.receive_text() ...