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

Path & Query Parameter

~10 min · fastapi, params, auth

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

Path param 은 REST 처럼

FastAPI 의 path parameter 가 WebSocket endpoint 에서도 똑같이 동작. @app.websocket('/ws/{room_id}')room_id: str 인자 줘. 자동 변환 위해 type-hint: room_id: int, user_id: UUID.

websocket.query_params 로 query param

브라우저 WebSocket constructor 에서 custom HTTP 헤더 못 박음 (Track 2). 그래서 query string 이 auth token, room name 등 handshake data 운반. websocket.query_params — string 의 dict-like mapping — 으로 읽어.

accept() 전에 validate

auth 와 reject 는 항상 accept() 전에. handshake 중 close 는 비용 0; accept 후 close 는 클라가 잠깐 'open' socket 본 다음 kick 보는 거 — 헷갈리는 UX 와 클라에서 mishandling 쉬움.

Code

Path + query + 빠른 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

/ws/{room_id} endpoint 추가하고 ?token=... 필수. token 없거나 decode_jwt 가 None 이면 code 4001 로 reject. 브라우저에서 valid token 과 invalid token 둘 다 테스트; valid 만 welcome message 까지 도달하는 거 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.