In FastAPI, how do you write a WebSocket endpoint with @app.websocket, and how does it receive, send and notice that the client left?
answer
- a decorator plus one typed parameter
- nothing flows before the handshake completes
- a loop of receive and send calls
- the exception a closed peer raises
basics
~10 sDecorate an async def with @app.websocket(path), take a websocket: WebSocket parameter, await websocket.accept(), then loop over receive_text() or receive_json() and send_text() or send_json(). When the client closes, the next receive raises WebSocketDisconnect.
solid answer
~40 sA WebSocket endpoint is an `async def` registered with `@app.websocket("/rooms/{room_id}/ws")` that takes a `websocket: WebSocket` parameter; path, query, header and cookie parameters and `Depends` work as on HTTP routes. Nothing can be sent until the handler awaits `websocket.accept()`, which completes the handshake. After that it usually loops: `await websocket.receive_text()` (or `receive_json()`, `receive_bytes()`) and `await websocket.send_text()` or `send_json()`. When the client closes, the pending receive raises `WebSocketDisconnect`, whose `code` holds the close code; catch it around the loop to remove the socket from any registry. Two things the route does not get: it is absent from the OpenAPI schema, and `send_json()` uses plain `json.dumps`, so a Pydantic model has to be dumped first with `model_dump(mode="json")`.
code
python · 14 linesfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
@app.websocket("/rooms/{room_id}/ws")
async def room_socket(websocket: WebSocket, room_id: str):
await websocket.accept()
try:
while True:
text = await websocket.receive_text()
await websocket.send_json({"room": room_id, "text": text})
except WebSocketDisconnect as exc:
print(f"left {room_id} with close code {exc.code}")go deeper
Recall the four moves: register with @app.websocket, await accept(), loop over receive and send, catch WebSocketDisconnect. Know that nothing can be sent before accept.
Explain that parameters and dependencies are resolved once at connect, that receive_json parses without validating, and that send_json uses plain json.dumps, so models are dumped first.
Show cleanup discipline: every exit path removes the socket from any registry, disconnects are treated as expected events, and every incoming message is validated before use.
Point out the contract gap: WebSocket routes are absent from the OpenAPI schema, so the team owns a documented, versioned message format and tests that pin it.
A **WebSocket endpoint** in FastAPI is an `async def` function registered with `@app.websocket(path)`, or `router.websocket(path)` on an `APIRouter`. A path operation turns one request into one response; a WebSocket endpoint instead holds one long-lived, two-way connection on which the client and the server can each send messages at any time until one side closes. The handler takes a parameter annotated `WebSocket` (importable from `fastapi`, re-exported from Starlette), and that object *is* the connection. The rest of the signature behaves as on HTTP routes: a path parameter such as `room_id: str` in `/rooms/{room_id}/ws` is parsed and validated, and `Query`, `Header`, `Cookie`, `Path`, `Depends` and `Security` are all supported. Those values are resolved **once, when the connection opens**, before the function body runs. ## The connection lifecycle 1. The client sends an HTTP upgrade request; FastAPI matches the route and resolves its parameters and dependencies. 2. The handler awaits `websocket.accept()`. Until then the handshake is still pending, and calling `receive_text()` raises a `RuntimeError` saying that `accept` must be called first. 3. The handler loops, awaiting messages and sending replies. 4. One side closes: the client by sending a close frame or by dropping the connection, the server by calling `websocket.close(code=...)`, raising `WebSocketException`, or returning from the function. ## Receiving and sending | Method on `WebSocket` | What it does | |---|---| | `receive_text()` | waits for the next text message and returns a `str` | | `receive_bytes()` | waits for the next binary message and returns `bytes` | | `receive_json()` | reads a text message and parses it with `json.loads` | | `send_text(data)` | sends a text message | | `send_bytes(data)` | sends a binary message | | `send_json(data)` | encodes `data` with `json.dumps` and sends it as text | | `iter_text()`, `iter_json()` | async iterators that end quietly when the client leaves | `receive_json()` parses but does not validate: malformed JSON raises `json.JSONDecodeError` out of the handler. To check a message against a Pydantic model, read the text and call the model's `model_validate_json()` yourself, catching its `ValidationError`. The server can end the conversation itself with `await websocket.close()`, whose `code` defaults to 1000 and whose optional `reason` travels to the client. To ask whether the socket is still open from the server's side, compare `websocket.application_state` with `WebSocketState.CONNECTED`, importable from `fastapi.websockets`. ## Noticing that the client left When the client closes, the next `receive_*` call raises **`WebSocketDisconnect`**. Its `code` attribute holds the close code the client sent (1000 for a normal close, 1001 when the client is going away, such as a page being closed), and `reason` holds the optional reason text. A connection that drops without a close frame surfaces with a code the server picks, such as 1006. The idiomatic shape is a `try` around the receive loop with `except WebSocketDisconnect:` doing the cleanup, such as removing the socket from a room's set of members. With `async for text in websocket.iter_text():` the loop simply ends on disconnect and the code after it runs, but the close code is no longer available. ```python @app.websocket("/rooms/{room_id}/ws") async def room_socket(websocket: WebSocket, room_id: str): await websocket.accept() try: while True: text = await websocket.receive_text() await websocket.send_json({"room": room_id, "text": text}) except WebSocketDisconnect as exc: print(f"left {room_id} with close code {exc.code}") ``` ## What the route does not get from FastAPI - **No OpenAPI entry.** WebSocket routes are left out of the generated schema, so `/docs` does not list them; the message format has to be documented elsewhere. - **No `response_model` and no Pydantic-side serialisation.** `@app.websocket` takes a path, a `name` and `dependencies`, nothing more. `send_json()` calls `json.dumps`, so passing a model raises `TypeError: Object of type ... is not JSON serializable`; send `model.model_dump(mode="json")` instead. - **No thread pool.** The handler must be `async def`. FastAPI awaits it directly, so a plain `def` handler fails with a `TypeError` as soon as a client connects. - **No message validation.** Only the parameters resolved at connect time are validated; every message is your code's job. ## Common mistakes - Sending before `accept()`, which raises instead of queuing the message. - Leaving out the `except WebSocketDisconnect`, so every ordinary disconnect ends the handler with an unhandled exception that the server logs as an error. - Cleaning up a registry only on the happy path, which leaves dead sockets behind for the next broadcast to trip over. - Expecting `send_json()` to handle models, datetimes or UUIDs the way a JSON response does.
- In FastAPI, what happens if a WebSocket handler calls receive_text() before accept()?Starlette's `WebSocket` refuses: the call raises a `RuntimeError` (in current Starlette, its `WebSocketDisconnected` subclass) saying that `accept` must be called first. The handshake is still pending at that point, so no message can flow either way. The only valid moves before accepting are `accept()` itself or closing, and closing refuses the connection.
- Can a FastAPI WebSocket endpoint be a plain def function, like a sync path operation?No. A `def` path operation runs in the thread pool, but a WebSocket route awaits the handler's return value directly. A `def` handler returns `None`, and awaiting it raises `TypeError: object NoneType can't be used in 'await' expression` as soon as a client connects. Write the handler as `async def` and move blocking work off the event loop explicitly.
- When is iter_text() a better fit than a while True loop around receive_text()?`async for text in websocket.iter_text():` stops quietly when the client disconnects, so the cleanup written after the loop runs without a `try`/`except`. It suits handlers that only need to know the client left. Keep the explicit loop with `except WebSocketDisconnect as exc:` when you need `exc.code` or want other exceptions handled differently.
- FastAPI accepts the socket automatically, so the handler can send straight away.
- A closed client makes receive_text() return an empty string.
- WebSocket endpoints appear in /docs like any other path operation.
- send_json() serialises a Pydantic model the way a response_model does.
- A WebSocket endpoint can be a def function that FastAPI runs in the thread pool.