Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using websocket.connect() instead of websocket.accept()
Trying to send data before accepting the connection
✗ Incorrect
You must call websocket.accept() to accept the WebSocket connection before sending or receiving data.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using receive_text() and then parsing JSON manually
Using receive_bytes() which returns raw bytes
✗ Incorrect
To receive JSON data, use websocket.receive_json() which parses the incoming message as JSON.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using disconnect() which is not a WebSocket method
Using reject() which does not exist
✗ Incorrect
To close a WebSocket connection with a code, use websocket.close(code).
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to send before accepting
Using send_json() with a string instead of a dict
✗ Incorrect
First accept the connection, then send a text message with send_text().
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong token string
Not closing connection on invalid token
Not accepting connection before receiving
✗ Incorrect
Check token against "secret", close connection if invalid, accept connection if valid.