How to Use WebSocket in FastAPI: Simple Guide with Example
To use
WebSocket in FastAPI, define an endpoint with websocket parameter and use await websocket.accept() to accept connections. Then, use await websocket.receive_text() and await websocket.send_text() to receive and send messages asynchronously.Syntax
In FastAPI, a WebSocket endpoint is defined using the @app.websocket() decorator. The function receives a WebSocket object to manage the connection.
- websocket.accept(): Accepts the WebSocket connection.
- websocket.receive_text(): Awaits and receives a text message from the client.
- websocket.send_text(): Sends a text message back to the client.
- websocket.close(): Closes the WebSocket connection.
python
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") await websocket.close()
Example
This example shows a simple FastAPI WebSocket server that accepts a connection, receives a message from the client, sends a response echoing the message, and then closes the connection.
python
from fastapi import FastAPI, WebSocket import uvicorn app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: try: data = await websocket.receive_text() await websocket.send_text(f"You wrote: {data}") except Exception: await websocket.close() break if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000)
Output
Running server on http://127.0.0.1:8000
WebSocket endpoint available at ws://127.0.0.1:8000/ws
Common Pitfalls
- Not accepting the connection: Forgetting
await websocket.accept()causes the client connection to hang. - Not handling disconnects: Not catching exceptions on receive can crash the server when clients disconnect.
- Blocking code: Using blocking calls inside async functions will freeze the server.
- Closing connection too early: Closing the WebSocket immediately after sending a message prevents further communication.
python
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): # Wrong: missing accept() data = await websocket.receive_text() # This will hang await websocket.send_text(f"Message: {data}") # Correct way: @app.websocket("/ws_correct") async def websocket_endpoint_correct(websocket: WebSocket): await websocket.accept() try: while True: data = await websocket.receive_text() await websocket.send_text(f"Message: {data}") except Exception: await websocket.close()
Quick Reference
Here is a quick summary of key WebSocket methods in FastAPI:
| Method | Description |
|---|---|
| websocket.accept() | Accepts the WebSocket connection from the client. |
| websocket.receive_text() | Waits for a text message from the client. |
| websocket.send_text(text) | Sends a text message to the client. |
| websocket.close() | Closes the WebSocket connection. |
| websocket.receive_bytes() | Receives binary data from the client. |
| websocket.send_bytes(data) | Sends binary data to the client. |
Key Takeaways
Always call await websocket.accept() to accept the WebSocket connection.
Use async receive and send methods to handle messages without blocking.
Handle exceptions to manage client disconnects gracefully.
Keep the connection open for ongoing communication unless you want to close it.
FastAPI WebSocket endpoints use the @app.websocket decorator and async functions.