skip to content

In FastAPI, how do you refuse a WebSocket connection with WebSocketException, and what does the client see before versus after accept()?

level: middleimportance: should knowfreq 30%

answer

  1. not the HTTP exception class
  2. the policy-violation close code
  3. where the handshake stands matters
  4. a refused handshake hides your code

basics

~20 s

Raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) from the endpoint or a dependency. Before accept(), Uvicorn refuses the handshake with HTTP 403 and the code never reaches the client; after accept(), the client gets a close frame with the code and reason.

solid answer

~40 s

`WebSocketException` is the WebSocket counterpart of `HTTPException`: raise it with a close `code`, usually `status.WS_1008_POLICY_VIOLATION`, and an optional `reason`, from the handler or from any dependency, and the exception middleware calls `websocket.close(code, reason)`. What the client sees depends on the handshake. Raised **before** `accept()`, the close is a refusal: Uvicorn answers the upgrade with HTTP 403, so the client sees a failed connection and never your code or reason. Raised **after** `accept()`, it becomes a real close frame whose code and reason the client can read. Parameter validation takes the first path: a missing or invalid query, header or cookie value raises `WebSocketRequestValidationError`, whose default handler closes with 1008 before the handler body runs. `HTTPException` is the wrong tool in a socket handler; the docs direct you to `WebSocketException`.

code

python · 26 lines
python
from typing import Annotated

from fastapi import FastAPI, Query, WebSocket, WebSocketException, status

app = FastAPI()
TOKENS = {"alice-token": "alice", "root-token": "admin"}


@app.websocket("/rooms/{room_id}/ws")
async def room_socket(
    websocket: WebSocket,
    room_id: str,
    token: Annotated[str | None, Query()] = None,
):
    user = TOKENS.get(token or "")
    if user is None:
        # Before accept(): the server refuses the handshake itself.
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    await websocket.accept()
    request = await websocket.receive_json()
    if request.get("join") == "staff" and user != "admin":
        # After accept(): the client receives a close frame with code and reason.
        raise WebSocketException(
            code=status.WS_1008_POLICY_VIOLATION, reason="not allowed in staff"
        )
    await websocket.send_json({"joined": request.get("join"), "user": user})

go deeper

for a junior

Remember the pairing: HTTPException for HTTP routes, WebSocketException with a close code such as status.WS_1008_POLICY_VIOLATION for sockets.

for a middle

Explain the before and after accept split: a close before accept is a refused handshake (403 under Uvicorn), a close after accept is a frame the client can read.

for a senior

Decide per failure where to refuse: unauthenticated clients before accept, errors the client must act on after accept with a short reason, and validation errors handled deliberately.

for a principal

Set one team convention for socket close codes and reasons, including any 4000-range codes, so clients and on-call engineers can tell failure causes apart.

FastAPI has a separate exception for WebSockets because a socket has no HTTP response to put a status code in. **`WebSocketException`** (importable from `fastapi`, a subclass of Starlette's class of the same name) takes a close `code` and an optional `reason` string. Its docstring scopes it to client errors such as invalid authentication or invalid data, not to bugs in your own code. ## The exception and where to raise it You can raise it from the endpoint body or from any dependency the endpoint uses. FastAPI's exception middleware catches it and calls `websocket.close(code=exc.code, reason=exc.reason)`. The codes are named in `fastapi.status`: - `status.WS_1008_POLICY_VIOLATION`, the usual choice for a missing or invalid credential or a forbidden action. - `status.WS_1003_UNSUPPORTED_DATA` for a payload type the endpoint cannot handle. - Codes in the 4000 to 4999 range, which the WebSocket specification leaves to applications, when the client needs to branch on your own reasons. ## What the client sees: before versus after accept() The same exception produces two different experiences, because `accept()` is the point where the handshake completes. | Raised | What the server does | What the client sees | |---|---|---| | before `accept()` | sends a close while the handshake is pending; Uvicorn turns that into an HTTP 403 answer to the upgrade | a failed connection, without your code or reason | | after `accept()` | sends a close frame with the code and reason | a normal close carrying `code` and `reason` | Refusing early is cheap and correct for unauthenticated clients: nothing is accepted and no resources are spent. Its cost is diagnostics, because a browser client cannot tell a bad token from a server that is down. When the client must know why, for example a member trying to join a room they may not enter, accept first and then raise with a short `reason`. ## Validation errors close the socket for you Parameters are resolved before the handler runs, so a validation failure always happens before `accept()`: 1. A client opens `/rooms/lobby/ws` without a required `token: Annotated[str, Query()]`. 2. FastAPI collects the errors and raises **`WebSocketRequestValidationError`** instead of `RequestValidationError`. 3. The default handler calls `websocket.close(code=WS_1008_POLICY_VIOLATION, reason=...)` with the encoded error list as the reason. 4. Under Uvicorn the client sees a 403 handshake refusal; there is no 422 JSON body as on HTTP routes. You can replace that behaviour with `@app.exception_handler(WebSocketRequestValidationError)`, for example to log `exc.errors()` or to accept and then close with a short reason a browser can read. ## What a reason may contain The `reason` string is shown to whoever opened the socket, so treat it as public output: - Keep it short and stable, such as `"token expired"` or `"not allowed in this room"`, so client code can match it. - Never put stack traces, internal identifiers or query details in it. - Use the same text whether a user does not exist or has the wrong token, so the reason cannot be used to probe accounts. - Log the detailed cause on the server instead, next to the room and user identifiers. ## Why not HTTPException The docs say plainly that an `HTTPException` makes little sense on a WebSocket and that `WebSocketException` is the one to raise. The mechanics show why: - **Before `accept()`**, FastAPI's HTTP exception handler builds its JSON error response, and Starlette sends it as a WebSocket denial response, an ASGI extension Uvicorn supports, so the upgrade fails with that HTTP status. It works, but only because of that extension, and it is easy to misread later. - **After `accept()`**, the same handler tries to send an HTTP response on an open socket. The server rejects it as an invalid ASGI message, and the client gets an abrupt end instead of a clean close code. ## Testing the two paths In-process tests do not go through Uvicorn, so they show the close code in both cases: `TestClient` raises `WebSocketDisconnect` with `code == 1008` either when the `with client.websocket_connect(...)` block is entered (refused before accept) or on the next receive (closed after accept). Keep that in mind when a test passes but a browser only reports "connection failed". ## Review checklist - Credentials are checked in a dependency that raises `WebSocketException` before `accept()`. - Errors the client must understand are raised after `accept()` with a short `reason`. - No `HTTPException` is raised from socket handlers or socket-only dependencies. - The validation-error handler is customised only if the team needs the errors logged or shown.

  • How do you change what FastAPI does when a WebSocket parameter fails validation?
    Register a handler with `@app.exception_handler(WebSocketRequestValidationError)` taking `(websocket, exc)`. The default one calls `websocket.close(code=1008, reason=...)` with the encoded errors as the reason. A custom one can log `exc.errors()`, or accept first and then close with a short reason a browser can read, since a close before `accept()` reaches the client only as a refused handshake.
  • What happens if a FastAPI WebSocket handler raises HTTPException(status_code=401)?
    It depends on the handshake. Before `accept()`, FastAPI's HTTP exception handler produces its JSON response, and Starlette sends it as a WebSocket denial response, which Uvicorn supports, so the upgrade fails with 401. After `accept()`, that HTTP response is not a valid message on an open socket; the server rejects it and the client sees an abrupt end rather than a clean close code. `WebSocketException` avoids both surprises.

  • WebSocketException raised before accept() delivers its code and reason to the browser.
  • Raising HTTPException(status_code=401) is the normal way to refuse a WebSocket.
  • A missing required query parameter on a WebSocket route returns a 422 JSON body.
  • accept() must be called before WebSocketException can be raised.
  • WebSocketException is meant for reporting bugs and server faults inside the handler.