How do you define a WebSocket endpoint in FastAPI?

async endpoint wiring and the accept-receive-send lifecycle.
import WebSocket, use @app.websocket, await accept, receive_text, then send_text.
forgetting accept or treating it like a standard HTTP route.
WHAT THIS TESTS: This question checks if you know the exact FastAPI WebSocket wiring beyond regular HTTP path operations. Interviewers want to see that you understand the handshake is explicit, the endpoint uses a different decorator, and the I/O is fully async. It also surfaces whether you know the correct imports and the basic message flow. At the senior level, they may also probe whether you understand that WebSockets are long-lived and stateful, but for this minimal version they mainly want clean syntax.
A GOOD ANSWER COVERS: First, the import: from fastapi import FastAPI, WebSocket. Second, the decorator: @app.websocket("/ws") instead of @app.get or @app.post. Third, the function signature must declare a websocket parameter typed as WebSocket, not Request. Fourth, the lifecycle: await websocket.accept to open the connection, await websocket.receive_text to read one message, and await websocket.send_text to reply. Fifth, mention that you must install the websockets package because FastAPI relies on it as the underlying protocol implementation. A strong candidate will state the steps in order without hesitation.
COMMON WRONG ANSWERS: Treating the endpoint like HTTP by using @app.get or injecting Request. Forgetting await websocket.accept, which causes the client to hang because the handshake never completes. Omitting await on receive_text or send_text, which breaks the async flow and raises runtime errors. Using websocket.receive instead of receive_text without explaining the bytes versus text distinction. Writing synchronous blocking code inside the WebSocket handler, such as heavy computation or time.sleep. Importing WebSocket from starlette instead of fastapi is technically functional but is less idiomatic and misses the point of using FastAPI's native abstraction.
LIKELY FOLLOW-UPS: How would you handle multiple messages in a loop? How do you manage disconnections and cleanup with try-finally or WebSocketDisconnect? Can you use Depends inside a WebSocket endpoint, and what are the caveats around authentication? How would you broadcast to multiple connected clients, perhaps using a connection manager? What is the difference between receive_text and receive_bytes, and when would you use each?
ONE CONCRETE EXAMPLE: from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}")
Source: fastapi.tiangolo.com
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.