0
0
FastAPIframework~10 mins

Why WebSockets enable real-time communication in FastAPI - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why WebSockets enable real-time communication
Client sends HTTP request to server
Server upgrades connection to WebSocket
Open two-way communication channel
Client and Server can send messages anytime
Messages received instantly without new HTTP requests
Connection stays open until closed by either side
The flow shows how a normal HTTP request upgrades to a WebSocket connection, enabling continuous two-way messaging without repeated requests.
Execution Sample
FastAPI
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}')
This FastAPI code opens a WebSocket endpoint that accepts a connection, receives a message, and sends a response back immediately.
Execution Table
StepActionState BeforeState AfterMessage Sent/Received
1Client sends HTTP request to /wsNo connectionRequest receivedNone
2Server upgrades to WebSocketRequest receivedWebSocket connection openNone
3Server accepts connectionWebSocket connection openConnection acceptedNone
4Client sends message 'Hello'Connection acceptedMessage receivedHello
5Server sends responseMessage receivedResponse sentReceived: Hello
6Connection remains openResponse sentConnection openNone
7Client or server closes connectionConnection openConnection closedNone
💡 Connection closes when either client or server ends it, stopping real-time communication.
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
websocket.connection_stateNoneOpenOpenOpenClosed
message_receivedNoneNone'Hello''Hello'None
message_sentNoneNoneNone'Received: Hello'None
Key Moments - 3 Insights
Why does the connection stay open after the first message?
Because WebSocket upgrades the HTTP connection to a persistent two-way channel, allowing multiple messages without reconnecting, as shown in steps 4-6 in the execution_table.
How does the server know when to send a message back?
The server waits for a message from the client (step 4), then immediately sends a response (step 5), demonstrating real-time interaction.
What happens if the client sends another message after step 5?
The connection is still open (step 6), so the server can receive and respond again without a new HTTP request.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the connection state after step 3?
AHTTP request pending
BWebSocket connection is open
CConnection is closed
DNo connection exists
💡 Hint
Check the 'State After' column for step 3 in the execution_table.
At which step does the server send a message back to the client?
AStep 5
BStep 4
CStep 6
DStep 7
💡 Hint
Look for 'Message Sent/Received' column showing a message sent by the server.
If the client never closes the connection, what happens to the connection state after step 6?
AServer closes connection after timeout
BConnection closes automatically
CConnection remains open for more messages
DConnection resets to HTTP
💡 Hint
Refer to the 'State After' column in step 6 and the exit_note.
Concept Snapshot
WebSockets start as HTTP requests that upgrade to a persistent two-way channel.
This lets client and server send messages anytime without reconnecting.
The connection stays open until closed by either side.
FastAPI handles this with @app.websocket and async functions.
This enables real-time communication like chat or live updates.
Full Transcript
WebSockets enable real-time communication by upgrading a normal HTTP request to a persistent two-way connection. In FastAPI, this is done using the @app.websocket decorator. The server accepts the WebSocket connection, then both client and server can send messages instantly without needing new HTTP requests. The connection remains open until closed by either side, allowing continuous real-time data exchange. This is shown step-by-step in the execution table, where the client sends a message, the server receives and responds immediately, and the connection stays open for more messages.