Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the FastAPI class.
FastAPI
from fastapi import [1] app = [1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing WebSocket instead of FastAPI
Using lowercase fastapi instead of FastAPI
✗ Incorrect
The FastAPI class is imported to create the app instance.
2fill in blank
mediumComplete the code to accept a WebSocket connection in FastAPI.
FastAPI
@app.websocket("/ws") async def websocket_endpoint(websocket: [1]): await websocket.accept()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request instead of WebSocket
Forgetting to accept the connection
✗ Incorrect
The WebSocket parameter type is used to handle WebSocket connections.
3fill in blank
hardFix the error in the code to send a message to the WebSocket client.
FastAPI
await websocket.[1](text_data="Hello Client")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using send_text which does not exist
Using send_json when sending plain text
✗ Incorrect
The correct method to send text data is send with the text_data argument.
4fill in blank
hardFill both blanks to broadcast a message to all connected clients stored in a list.
FastAPI
clients = [] async def broadcast(message): for client in clients: await client.[1](text_data=[2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using receive instead of send
Using send_text which is not a valid method
✗ Incorrect
To send a message to each client, use send with the message variable.
5fill in blank
hardFill all three blanks to add a new WebSocket client to the list and broadcast a welcome message.
FastAPI
clients = [] @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() clients.[1](websocket) await broadcast([2]) async def broadcast(message): for client in clients: await client.send(text_data=[3])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using remove instead of append
Sending the wrong variable in broadcast
✗ Incorrect
Use append to add the client, send a welcome string, and broadcast the message variable.