In FastAPI, WebSockets allow continuous communication between client and server. How do WebSockets keep this connection open?
Think about a phone call that stays connected instead of hanging up after each sentence.
WebSockets create a single TCP connection that remains open, allowing messages to flow instantly both ways without reopening connections.
Consider a FastAPI WebSocket endpoint that echoes messages back to the client. What is the expected behavior when the client sends a message?
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): await websocket.accept() data = await websocket.receive_text() await websocket.send_text(f'Message received: {data}')
Look at the send_text line and what it sends back.
The server accepts the WebSocket connection, waits for a text message, then sends back a confirmation including the received message.
Which option contains the correct syntax for accepting a WebSocket connection and receiving a text message?
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): await websocket.accept() data = await websocket.receive_text() await websocket.send_text(f'Received: {data}')
Check for missing await keywords and function definitions.
Option C correctly uses async def and awaits all async calls. Option C misses awaits, C is not async, and D misses parentheses on accept.
Given this FastAPI WebSocket code that counts messages, what is the value of count after receiving three messages?
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): await websocket.accept() count = 0 for _ in range(3): await websocket.receive_text() count += 1 await websocket.send_text(f'Messages received: {count}')
Count increments inside the loop for each message received.
The loop runs three times, each time receiving a message and increasing count by 1, so count is 3.
Examine this WebSocket endpoint code. Why does it raise a RuntimeError: Cannot call receive_text() after connection is closed?
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): await websocket.accept() data = await websocket.receive_text() await websocket.close() data2 = await websocket.receive_text()
Think about what happens after closing a connection.
After calling await websocket.close(), the connection is closed. Trying to receive another message causes a RuntimeError.