0
0
FastAPIframework~3 mins

Why WebSocket endpoint creation in FastAPI? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to make your apps truly live and interactive with just a few lines of code!

The Scenario

Imagine building a chat app where you have to refresh the page every time a new message arrives.

You try to keep the conversation live by constantly asking the server for updates, but it feels slow and clunky.

The Problem

Manually polling the server wastes bandwidth and causes delays.

It's hard to keep the chat smooth and real-time.

Plus, writing all the code to handle connections, messages, and errors is complicated and repetitive.

The Solution

WebSocket endpoints let your app keep a live connection open with the server.

This means messages flow instantly both ways without refreshing or waiting.

FastAPI makes creating these endpoints simple and clean, handling the tricky parts for you.

Before vs After
Before
while True:
    response = requests.get('/messages')
    print(response.json())
    time.sleep(5)
After
from fastapi import WebSocket
from fastapi import FastAPI

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}')
What It Enables

You can build real-time apps like chats, live notifications, or games that feel instant and responsive.

Real Life Example

Think of a live sports score app that updates scores the moment a goal is scored without you clicking refresh.

Key Takeaways

Polling the server is slow and wastes resources.

WebSocket endpoints keep a live, two-way connection open.

FastAPI simplifies creating these real-time communication channels.