
WebSockets in FastAPI
What are WebSockets?
WebSockets allow a client and server to talk to each other continuously.
Normally, with HTTP, the client asks the server for something, and the server sends a response.
With WebSockets, the connection stays open, so both sides can send messages whenever they want.
Simple Example
Think of a phone call:
- HTTP → You call, ask a question, get an answer, and the conversation ends.
- WebSocket → You stay on the call and both people can talk anytime.
Why use WebSockets?
WebSockets are useful when we need real-time updates, such as:
- Chat applications
- Online games
- Live dashboards
- Notifications
- Live location tracking
- Real-time stock prices
WebSockets in FastAPI
FastAPI makes WebSockets easy to create.
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket(websocket: WebSocket):
await websocket.accept()
while True:
message = await websocket.receive_text()
await websocket.send_text(f"You said: {message}")
What happens here?
- The client connects to websocket
accept()accepts the connection.- The server waits for a message.
receive_text()receives the message.send_text()sends a response.- The connection stays open because of the while true loop.
HTTP vs WebSocket
| HTTP | WebSocket |
|---|---|
| Request → Response | Continuous connection |
| Connection usually ends after response | Connection stays open |
| Good for normal APIs | Good for real-time communication |
| Example: Login API | Example: Chat app |

Simple Example
Imagine a chat app.
When you send "Hello", the server immediately receives it and can send back "Hello!" without creating a new connection every time.
In short
WebSocket = a permanent connection between the client and server for real-time communication.
Join Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments