C.W.K.
Stream
Lesson 05 of 08 · published

Path & Query Parameters

~10 min · fastapi, params, auth

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Path params work like REST

FastAPI's path parameters work identically for WebSocket endpoints. @app.websocket('/ws/{room_id}') gives you a room_id: str argument. Type-hint it for automatic conversion: room_id: int, user_id: UUID, etc.

Query params via websocket.query_params

Custom HTTP headers are not settable from the browser WebSocket constructor (Track 2). So query strings carry the auth token, room name, and other handshake data. Read them via websocket.query_params — a dict-like mapping of strings.

Validate before accept()

Always validate auth and reject before accept(). Closing during the handshake costs nothing; closing after accept means the client briefly sees an "open" socket and then a kick — confusing UX and easier to mishandle on the client.

Code

Path + query + early reject·python
from fastapi import FastAPI, WebSocket
from uuid import UUID

app = FastAPI()

@app.websocket('/ws/{room_id}')
async def room(websocket: WebSocket, room_id: UUID):
    token = websocket.query_params.get('token')
    user = decode_jwt(token) if token else None
    if not user:
        # Reject before handshake completes — no .accept() yet
        await websocket.close(code=4001, reason='unauthorized')
        return

    await websocket.accept()
    await websocket.send_json({
        'type': 'welcome',
        'data': {'room': str(room_id), 'user': user['name']}
    })
    # ... continue handler

External links

Exercise

Add a /ws/{room_id} endpoint that requires ?token=.... Reject with code 4001 if the token is missing or decode_jwt returns None. Test from the browser with both a valid and an invalid token; confirm only the valid one ever reaches the welcome message.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.