
03/11/2024
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!
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.
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]
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
FastAPI, WebSocket, and HTMLResponse.WebSocket connection is established in the browser using JavaScript./ws endpoint is defined to handle WebSocket connections. Inside the websocket_endpoint function:
await websocket.accept(): This line accepts the incoming WebSocket connection.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.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.
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.
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.
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.
04/11/2024 | Python
03/11/2024 | Python
04/11/2024 | Python
04/11/2024 | Python
03/11/2024 | Python
04/11/2024 | Python
03/11/2024 | Python