logologo
  • Dashboard
  • Features
  • AI Tools
  • FAQs
  • Jobs
  • Modus
logologo

We source, screen & deliver pre-vetted developers—so you only interview high-signal candidates matched to your criteria.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • Pre-Vetted Top Developers

Procodebase © 2025. All rights reserved.

Q: How to handle websockets in FastAPI?

author
Generated by
ProCodebase AI

03/11/2024

FastAPI

FastAPI is an excellent choice for building modern web applications that require real-time communication, thanks to its support for WebSockets. In this guide, we’ll explore how to implement WebSockets with FastAPI from scratch. Let’s dive in!

What are WebSockets?

WebSockets are a protocol used to establish a continuous two-way connection between a client and a server. Unlike traditional HTTP requests, WebSockets allow for persistent communication so that both parties can send messages to each other at any time. This feature makes WebSockets perfect for applications such as chat apps, live notifications, and real-time data feeds.

Setting Up a FastAPI Project

To get started, you’ll need to have Python installed. If you haven't already installed FastAPI and the necessary WebSocket library, you can install it using pip:

pip install fastapi[all]

Creating a Simple WebSocket Server

Here’s a basic FastAPI application that sets up a WebSocket endpoint:

from fastapi import FastAPI, WebSocket from fastapi.responses import HTMLResponse app = FastAPI() html = """ <!DOCTYPE html> <html> <head> <title>WebSocket Example</title> </head> <body> <h1>WebSocket Example</h1> <textarea id="messages" cols="30" rows="10"></textarea><br> <input id="input" type="text"/><button onclick="sendMessage()">Send</button> <script> var ws = new WebSocket("ws://localhost:8000/ws"); ws.onmessage = function(event) { document.getElementById("messages").value += event.data + '\\n'; }; function sendMessage() { var input = document.getElementById("input"); ws.send(input.value); input.value = ''; } </script> </body> </html> """ @app.get("/") async def get(): return HTMLResponse(html) @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() # Accept the WebSocket connection while True: data = await websocket.receive_text() # Receive a message from the client await websocket.send_text(f"Message text was: {data}") # Send a response back

Explanation of the Code

  1. Imports: We import FastAPI, WebSocket, and HTMLResponse.
  2. Creating the HTML Page: The HTML contains a simple user interface with a textarea for displaying messages and an input field for sending messages. The WebSocket connection is established in the browser using JavaScript.
  3. FastAPI App: We instantiate a FastAPI application.
  4. WebSocket Endpoint: The /ws endpoint is defined to handle WebSocket connections. Inside the websocket_endpoint function:
    • await websocket.accept(): This line accepts the incoming WebSocket connection.
    • A while True loop is initiated to continuously listen for messages.
    • await websocket.receive_text(): This line awaits messages sent by the client.
    • await websocket.send_text(): This sends back a formatted response.

Running the Application

Save the code above to a file named main.py. You can start the FastAPI application by using Uvicorn, an ASGI server, with the following command:

uvicorn main:app --reload

Once the server is running, you can navigate to http://localhost:8000 in your web browser to see the application in action.

Testing the WebSocket Connection

You will see a text area and a text input field. Start typing messages and click “Send.” Each message you send will be returned by the server prefixed with "Message text was: ", demonstrating real-time communication.

Handling Connection Closure

It’s also crucial to handle cases where a WebSocket connection might close unexpectedly. You can enhance the server by implementing exception handling around your message receiving block:

try: while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") except Exception as e: print(f"Connection closed with error: {e}")

With these additions, the server can gracefully terminate the connection and inform the appropriate parties.

Conclusion

By following these steps, you've successfully created a simple WebSocket server using FastAPI. You can expand this example further, adding features like broadcasting messages to all connected clients, managing multiple rooms, or integrating it with databases for storing messages. FastAPI’s efficient handling of asynchronous operations makes it an ideal framework for building real-time applications.

Popular Tags

FastAPIWebSocketsPython

Share now!

Related Questions

  • How to create a violin plot in Seaborn

    04/11/2024 | Python

  • How to handle background tasks in FastAPI

    03/11/2024 | Python

  • Explain TensorFlow's autograph feature

    04/11/2024 | Python

  • What are class-based views and how do they differ from function-based views

    04/11/2024 | Python

  • Write a FastAPI app with async database access

    03/11/2024 | Python

  • Implement a custom loss function in TensorFlow

    04/11/2024 | Python

  • Explain dependency injection in FastAPI

    03/11/2024 | Python

Popular Category

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