📖 Scenario: You are building a simple chat server using FastAPI. You want to understand how WebSockets help send messages instantly between clients without waiting for page reloads.
🎯 Goal: Create a FastAPI app that sets up a WebSocket endpoint to accept connections and broadcast messages to all connected clients in real time.
📋 What You'll Learn
Create a FastAPI app instance named app
Create a list called connections to store active WebSocket connections
Add a WebSocket route at /ws that accepts connections
Implement logic to receive messages from one client and send them to all connected clients immediately
💡 Why This Matters
🌍 Real World
WebSockets are used in chat apps, live notifications, online games, and any app needing instant updates without page reloads.
💼 Career
Understanding WebSockets is key for backend developers building real-time features and for full-stack developers integrating live user experiences.
Progress0 / 4 steps
1
Create FastAPI app and connections list
Create a FastAPI app instance called app and a list called connections to hold active WebSocket connections.
FastAPI
Hint
Use app = FastAPI() to create the app and connections = [] to store WebSocket clients.
2
Add WebSocket endpoint at /ws
Add a WebSocket route at /ws using @app.websocket("/ws") and define an async function websocket_endpoint that accepts a websocket parameter of type WebSocket. Inside, accept the connection with await websocket.accept().
FastAPI
Hint
Use @app.websocket("/ws") decorator and inside the function call await websocket.accept() to accept the connection.
3
Add connection to list and broadcast messages
Inside websocket_endpoint, add the websocket to the connections list. Then create a while True loop to receive messages with data = await websocket.receive_text(). For each message, send it to all websockets in connections using await connection.send_text(data).
FastAPI
Hint
Remember to add the websocket to connections and use a loop to receive and broadcast messages.
4
Handle disconnects and remove connections
Wrap the message receiving and sending loop in a try block. Use except WebSocketDisconnect to catch disconnects and remove the websocket from connections with connections.remove(websocket).
FastAPI
Hint
Use try and except WebSocketDisconnect to handle client disconnects and remove them from the list.
Practice
(1/5)
1. Why do WebSockets enable real-time communication in FastAPI applications?
easy
A. Because they only send data from server to client once
B. Because they use HTTP requests repeatedly to fetch new data
C. Because they keep a constant open connection for instant two-way data exchange
D. Because they require manual page refresh to update data
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 C
Quick Check:
Persistent connection = real-time communication [OK]
Hint: Remember: WebSockets keep connection open for instant updates [OK]
Common Mistakes:
Confusing WebSockets with repeated HTTP requests
Thinking WebSockets only send data one way
Assuming page refresh is needed for updates
2. Which of the following is the correct way to define a WebSocket route in FastAPI?
easy
A. app.websocket('/ws') async def websocket_endpoint(websocket): await websocket.accept()
B. app.get('/ws') async def websocket_endpoint(websocket): await websocket.accept()
C. app.post('/ws') def websocket_endpoint(websocket): websocket.accept()
D. app.websocket('/ws') def websocket_endpoint(): websocket.accept()
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 A
Quick Check:
Use @app.websocket + async + await accept() [OK]
Hint: WebSocket routes need @app.websocket and async functions [OK]
Common Mistakes:
Using HTTP method decorators like @app.get for WebSockets
Forgetting async or await keywords
Defining function without websocket parameter
3. Given this FastAPI WebSocket code snippet, what will the client receive after sending 'hello'?