0
0
FastAPIframework~10 mins

Broadcasting to multiple clients 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 import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AFastAPI
BRequest
CDepends
DWebSocket
Attempts:
3 left
💡 Hint
Common Mistakes
Importing WebSocket instead of FastAPI
Using lowercase fastapi instead of FastAPI
2fill in blank
medium

Complete 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'
ARequest
BDepends
CWebSocket
DResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request instead of WebSocket
Forgetting to accept the connection
3fill in blank
hard

Fix 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'
Asend_message
Bsend_json
Csend_text
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using send_text which does not exist
Using send_json when sending plain text
4fill in blank
hard

Fill 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'
Asend
Breceive
Csend_text
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using receive instead of send
Using send_text which is not a valid method
5fill in blank
hard

Fill 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'
Aappend
B"Welcome new client!"
Cmessage
Dremove
Attempts:
3 left
💡 Hint
Common Mistakes
Using remove instead of append
Sending the wrong variable in broadcast