WebSockets let your app talk back and forth instantly without waiting. This makes real-time updates possible, like chat or live scores.
Why WebSockets enable real-time communication in FastAPI
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}")
Use @app.websocket to create a WebSocket route.
Call await websocket.accept() to start the connection.
await websocket.accept()data = await websocket.receive_text()await websocket.send_text(f"Echo: {data}")
This FastAPI app opens a WebSocket at /ws. When a client connects and sends a message, the server replies immediately with the same message prefixed by 'You said:'. This shows real-time two-way communication.
from fastapi import FastAPI, WebSocket import uvicorn app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"You said: {data}") if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000)
WebSockets keep the connection open, unlike normal HTTP requests that close after response.
This makes WebSockets perfect for live updates without repeated requests.
Remember to handle connection closing and errors in real apps.
WebSockets allow instant two-way communication between client and server.
FastAPI supports WebSockets with simple async functions and decorators.
This enables real-time features like chat, live data, and notifications.
Practice
Solution
Step 1: Understand WebSocket connection behavior
WebSockets maintain a persistent connection allowing continuous data flow without reconnecting.Step 2: Compare with HTTP request-response model
Unlike HTTP, which closes after each request, WebSockets allow instant two-way communication.Final Answer:
Because they keep a constant open connection for instant two-way data exchange -> Option CQuick Check:
Persistent connection = real-time communication [OK]
- Confusing WebSockets with repeated HTTP requests
- Thinking WebSockets only send data one way
- Assuming page refresh is needed for updates
Solution
Step 1: Identify correct decorator and async function
FastAPI uses @app.websocket decorator and async def for WebSocket routes.Step 2: Confirm usage of await websocket.accept()
Accepting the connection requires awaiting websocket.accept() inside async function.Final Answer:
app.websocket('/ws') async def websocket_endpoint(websocket): await websocket.accept() -> Option AQuick Check:
Use @app.websocket + async + await accept() [OK]
- Using HTTP method decorators like @app.get for WebSockets
- Forgetting async or await keywords
- Defining function without websocket parameter
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}')Solution
Step 1: Analyze the receive and send calls
The server waits for text, receives 'hello', then sends back 'Received: hello'.Step 2: Confirm connection acceptance
websocket.accept() is awaited, so connection is open and ready for communication.Final Answer:
'Received: hello' -> Option DQuick Check:
Server echoes with prefix 'Received:' [OK]
- Assuming no response is sent
- Ignoring the awaited accept() call
- Confusing received data with sent data
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
data = await websocket.receive_text()
await websocket.accept()
await websocket.send_text(f'Got: {data}')Solution
Step 1: Check order of accept and receive calls
WebSocket connection must be accepted before receiving data.Step 2: Identify the error caused by wrong order
Calling receive_text before accept() causes runtime error as connection is not open yet.Final Answer:
Calling receive_text before accepting the connection -> Option BQuick Check:
Accept connection before receiving data [OK]
- Receiving data before accepting connection
- Forgetting async keyword
- Confusing send_text with send_bytes
Solution
Step 1: Understand real-time broadcast requirement
To update all clients instantly, server must send messages to all open connections.Step 2: Identify best method for broadcasting
Maintaining a list of connected WebSocket objects allows sending messages to all clients immediately.Final Answer:
Keep a list of connected WebSocket objects and broadcast messages to all -> Option AQuick Check:
Broadcast via open WebSocket connections = real-time updates [OK]
- Using repeated HTTP polling instead of WebSockets
- Opening new connections per message wastes resources
- Relying on database triggers without WebSocket communication
Ready to prove it?
Pass the test and this pattern moves unknown
