0
0
FastAPIframework~10 mins

Why WebSockets enable real-time communication in FastAPI - Test Your Understanding

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

Complete the code to import the WebSocket class from FastAPI.

FastAPI
from fastapi import [1]
Drag options to blanks, or click blank then click option'
AResponse
BWebSocket
CRequest
DDepends
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request or Response instead of WebSocket.
Forgetting to import WebSocket causes errors when using it.
2fill in blank
medium

Complete the code to accept a WebSocket connection inside an endpoint.

FastAPI
async def websocket_endpoint(websocket: WebSocket):
    await websocket.[1]()
Drag options to blanks, or click blank then click option'
Aaccept
Bclose
Csend_text
Dreceive_text
Attempts:
3 left
💡 Hint
Common Mistakes
Calling send_text before accepting the connection.
Not calling accept causes the connection to be rejected.
3fill in blank
hard

Fix the error in the code to receive a message from the client.

FastAPI
data = await websocket.[1]()
Drag options to blanks, or click blank then click option'
Asend_text
Baccept
Creceive_text
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using send_text instead of receive_text.
Trying to accept or close instead of receiving data.
4fill in blank
hard

Fill both blanks to send a message back to the client with the received data.

FastAPI
await websocket.[1](text='Message received: ' + [2])
Drag options to blanks, or click blank then click option'
Asend_text
Bdata
Creceive_text
Daccept
Attempts:
3 left
💡 Hint
Common Mistakes
Using receive_text instead of send_text to send data.
Using accept or close instead of send_text.
Using receive_text or accept instead of the data variable.
5fill in blank
hard

Fill all three blanks to create a simple FastAPI WebSocket app that echoes messages.

FastAPI
from fastapi import FastAPI, [1]

app = FastAPI()

@app.websocket('/ws')
async def websocket_endpoint(websocket: [2]):
    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'
AWebSocket
BRequest
Caccept
DResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using Request or Response instead of WebSocket.
Forgetting to call accept() before communication.