Building an asynchronous WebSocket
Unlike in SSE, connection in WebSocket is always bi-directional, which means the server and client communicate with each other using a long TCP socket connection. The communication is always in real time and it doesn’t require the client or the server to reply to every event sent.
Implementing the asynchronous WebSocket endpoint
The FastAPI framework allows the implementation of an asynchronous WebSocket that can also run on the HTTP/2 protocol. The following is an example of an asynchronous WebSocket created using the coroutine block:
import asyncio from fastapi import WebSocket @router.websocket("/customer/list/ws") async def customer_list_ws(websocket: WebSocket): await websocket.accept() repo = CustomerRepository() result = await repo.get_all_customer() for rec in result: ...