ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Unleashing Real-Time Power

author
Generated by
Shahrukh Quraishi

15/10/2024

fastapi

Sign in to read full article

Introduction to WebSockets

In the era of instant communication and live updates, WebSockets have become a game-changer for web developers. Unlike traditional HTTP requests, WebSockets allow for full-duplex, bidirectional communication between clients and servers. This means your application can send and receive messages in real-time without the need for constant polling.

FastAPI, our beloved high-performance Python web framework, comes with built-in support for WebSockets. Let's explore how we can harness this power to create dynamic, responsive applications.

Setting Up WebSocket Support in FastAPI

To get started with WebSockets in FastAPI, you'll need to install the websockets library:

pip install websockets

Now, let's create a simple WebSocket endpoint:

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 received: {data}")

In this example, we've created a WebSocket endpoint at /ws. The websocket_endpoint function is an asynchronous function that accepts a WebSocket connection, receives messages, and echoes them back to the client.

Handling WebSocket Connections

When a client connects to your WebSocket endpoint, you need to explicitly accept the connection:

await websocket.accept()

After accepting the connection, you can start sending and receiving messages. The receive_text() method waits for incoming messages, while send_text() sends messages back to the client.

Broadcasting Messages

One of the most powerful features of WebSockets is the ability to broadcast messages to multiple clients. Let's create a simple chat room:

from fastapi import FastAPI, WebSocket from typing import List app = FastAPI() class ConnectionManager: def __init__(self): self.active_connections: List[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) manager = ConnectionManager() @app.websocket("/ws/{client_id}") async def websocket_endpoint(websocket: WebSocket, client_id: int): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(f"Client #{client_id}: {data}") except WebSocketDisconnect: manager.disconnect(websocket) await manager.broadcast(f"Client #{client_id} left the chat")

In this example, we've created a ConnectionManager class to handle multiple WebSocket connections. When a client connects, we add them to the list of active connections. When a message is received, we broadcast it to all connected clients.

Handling WebSocket Disconnections

It's important to handle disconnections gracefully. In the example above, we use a try-except block to catch WebSocketDisconnect exceptions. When a client disconnects, we remove them from the active connections and notify other clients.

Advanced WebSocket Features

FastAPI's WebSocket support doesn't stop at basic messaging. You can also:

  1. Send and receive binary data:

    binary_data = await websocket.receive_bytes() await websocket.send_bytes(processed_data)
  2. Handle WebSocket subprotocols:

    @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept(subprotocol="custom_protocol")
  3. Implement authentication for WebSocket connections:

    @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket, token: str = Query(...)): if not is_valid_token(token): await websocket.close(code=status.WS_1008_POLICY_VIOLATION) return await websocket.accept()

Performance Considerations

While WebSockets are powerful, they can be resource-intensive if not used properly. Here are some tips to optimize your WebSocket usage:

  1. Limit the number of concurrent connections to prevent server overload.
  2. Implement a heartbeat mechanism to detect and close inactive connections.
  3. Use message queues for handling high-volume broadcasts.

Testing WebSocket Endpoints

Testing WebSocket endpoints can be challenging, but FastAPI makes it easier with its TestClient. Here's a simple example:

from fastapi.testclient import TestClient client = TestClient(app) def test_websocket(): with client.websocket_connect("/ws") as websocket: websocket.send_text("Hello, WebSocket!") data = websocket.receive_text() assert data == "Message received: Hello, WebSocket!"

This test connects to the WebSocket endpoint, sends a message, and verifies the response.

By integrating WebSockets into your FastAPI applications, you open up a world of possibilities for real-time features. From live chat systems to real-time data visualization, WebSockets empower you to create dynamic, responsive web applications that keep users engaged and informed.

Popular tags

fastapiwebsocketsreal-time

Share now!

Like & bookmark

Related collections

  • Mastering Scikit-learn from Basics to Advanced

    15/11/2024 · Python

  • Mastering NumPy: From Basics to Advanced

    25/09/2024 · Python

  • Matplotlib Mastery: From Plots to Pro Visualizations

    05/10/2024 · Python

  • LlamaIndex: Data Framework for LLM Apps

    05/11/2024 · Python

  • Python Basics: Comprehensive Guide

    21/09/2024 · Python

Related articles

  • Diving Deep into Tokenization with spaCy

    22/11/2024 · Python

  • Mastering Scikit-learn

    15/11/2024 · Python

  • Django Unveiled

    26/10/2024 · Python

  • Mastering Subplots and Multiple Figures in Matplotlib

    05/10/2024 · Python

  • Debugging and Testing Python Code

    21/09/2024 · Python

  • Mastering Context Window Management in Python with LlamaIndex

    05/11/2024 · Python

  • Enhancing Python Applications with Retrieval Augmented Generation using LlamaIndex

    05/11/2024 · Python

Popular category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design