0
0
FastAPIframework~10 mins

WebSocket endpoint creation 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 WebSocket class from FastAPI.

FastAPI
from fastapi import [1]
Drag options to blanks, or click blank then click option'
AWebSocket
BRequest
CDepends
DHTTPException
Attempts:
3 left
💡 Hint
Common Mistakes
Importing unrelated classes like Request or Depends.
Forgetting to import WebSocket causes errors when defining the endpoint.
2fill in blank
medium

Complete the code to define a WebSocket endpoint path '/ws'.

FastAPI
@app.websocket("[1]")
def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
Drag options to blanks, or click blank then click option'
A/socket
B/ws
C/websocket
D/chat
Attempts:
3 left
💡 Hint
Common Mistakes
Using HTTP route decorators like @app.get instead of @app.websocket.
Missing the leading slash in the path string.
3fill in blank
hard

Fix the error in the code to accept the WebSocket connection properly.

FastAPI
async def websocket_endpoint(websocket: WebSocket):
    await websocket.[1]()
Drag options to blanks, or click blank then click option'
Aconnect
Bstart
Caccept
Dopen
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like connect() or open() causes runtime errors.
Forgetting to accept the connection leads to client connection failures.
4fill in blank
hard

Fill both blanks to receive a text message and send it back to the client.

FastAPI
data = await websocket.[1]()
await websocket.[2](data)
Drag options to blanks, or click blank then click option'
Areceive_text
Bsend_text
Creceive_bytes
Dsend_bytes
Attempts:
3 left
💡 Hint
Common Mistakes
Using receive_bytes() when expecting text causes type errors.
Sending bytes when client expects text causes message format errors.
5fill in blank
hard

Fill all three blanks to create a complete WebSocket echo endpoint that accepts, receives, sends, and closes the connection.

FastAPI
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/echo")
async def echo_endpoint(websocket: WebSocket):
    await websocket.[1]()
    data = await websocket.[2]()
    await websocket.[3](data)
    await websocket.close()
Drag options to blanks, or click blank then click option'
Aaccept
Breceive_text
Csend_text
Dconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'connect' instead of 'accept' causes errors.
Mixing receive_text with send_bytes or vice versa causes message format issues.