0
0
FastAPIframework~10 mins

WebSocket authentication in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to accept a WebSocket connection in FastAPI.

FastAPI
from fastapi import FastAPI, WebSocket
app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.[1]()
    await websocket.send_text("Connected")
Drag options to blanks, or click blank then click option'
Aopen
Baccept
Cconnect
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Using websocket.connect() instead of websocket.accept()
Trying to send data before accepting the connection
2fill in blank
medium

Complete the code to receive a JSON message from the WebSocket.

FastAPI
data = await websocket.[1]()
Drag options to blanks, or click blank then click option'
Areceive_text
Breceive_data
Creceive_bytes
Dreceive_json
Attempts:
3 left
💡 Hint
Common Mistakes
Using receive_text() and then parsing JSON manually
Using receive_bytes() which returns raw bytes
3fill in blank
hard

Fix the error in the code to check a token from query parameters during WebSocket connection.

FastAPI
token = websocket.query_params.get("token")
if not token or token != "secret":
    await websocket.[1](1008)
    return
Drag options to blanks, or click blank then click option'
Areject
Bdisconnect
Cclose
Dabort
Attempts:
3 left
💡 Hint
Common Mistakes
Using disconnect() which is not a WebSocket method
Using reject() which does not exist
4fill in blank
hard

Fill both blanks to send a welcome message including the username after authentication.

FastAPI
username = websocket.query_params.get("username")
await websocket.[1]()
await websocket.[2](f"Welcome, {username}!")
Drag options to blanks, or click blank then click option'
Aaccept
Bsend_text
Csend_json
Dconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to send before accepting
Using send_json() with a string instead of a dict
5fill in blank
hard

Fill all three blanks to implement a WebSocket endpoint that authenticates by token, accepts connection, and echoes received messages.

FastAPI
from fastapi import FastAPI, WebSocket
app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    token = websocket.query_params.get("token")
    if token != [1]:
        await websocket.[2](1008)
        return
    await websocket.[3]()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Echo: {data}")
Drag options to blanks, or click blank then click option'
A"secret"
Bclose
Caccept
D"token"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong token string
Not closing connection on invalid token
Not accepting connection before receiving