0
0
FastAPIframework~5 mins

WebSocket endpoint creation in FastAPI

Choose your learning style9 modes available
Introduction

WebSocket endpoints let your app talk to users instantly without waiting. This is great for live chats or real-time updates.

You want to build a live chat app where messages appear instantly.
You need to show real-time notifications or alerts to users.
You want to update a dashboard with live data without refreshing the page.
You are making a multiplayer game that needs fast communication.
You want to stream data continuously, like stock prices or sensor info.
Syntax
FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

Use @app.websocket("/path") to create a WebSocket endpoint.

Call await websocket.accept() to accept the connection before communication.

Examples
A simple WebSocket that accepts one message and replies back.
FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/chat")
async def chat(websocket: WebSocket):
    await websocket.accept()
    data = await websocket.receive_text()
    await websocket.send_text(f"You said: {data}")
This endpoint echoes back every message it receives in a loop.
FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/echo")
async def echo(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(data)
Sample Program

This program creates a WebSocket endpoint at /ws. It accepts connections, waits for text messages, and sends back a reply showing what was received.

FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")
OutputSuccess
Important Notes

Always call await websocket.accept() to start the connection.

Use await websocket.receive_text() to get messages from the client.

Use await websocket.send_text() to send messages back.

Summary

WebSocket endpoints let your app communicate instantly with users.

Use @app.websocket decorator to create them in FastAPI.

Remember to accept connections and handle messages asynchronously.