WebSocket endpoints let your app talk to users instantly without waiting. This is great for live chats or real-time updates.
WebSocket endpoint creation in FastAPI
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 text was: {data}")
Use @app.websocket("/path") to create a WebSocket endpoint.
Call await websocket.accept() to accept the connection before communication.
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/chat") async def chat(websocket: WebSocket): await websocket.accept() data = await websocket.receive_text() await websocket.send_text(f"You said: {data}")
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/echo") async def echo(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data)
This program creates a WebSocket endpoint at /ws. It accepts connections, waits for text messages, and sends back a reply showing what was received.
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 text was: {data}")
Always call await websocket.accept() to start the connection.
Use await websocket.receive_text() to get messages from the client.
Use await websocket.send_text() to send messages back.
WebSocket endpoints let your app communicate instantly with users.
Use @app.websocket decorator to create them in FastAPI.
Remember to accept connections and handle messages asynchronously.
Practice
Solution
Step 1: Understand FastAPI endpoint decorators
FastAPI uses different decorators for different endpoint types: @app.get for GET HTTP, @app.post for POST HTTP, and @app.websocket for WebSocket connections.Step 2: Identify the correct decorator for WebSocket
Since WebSocket is a different protocol from HTTP, FastAPI uses @app.websocket to create WebSocket endpoints.Final Answer:
@app.websocket -> Option AQuick Check:
WebSocket endpoint decorator = @app.websocket [OK]
- Using @app.get or @app.post instead of @app.websocket
- Confusing HTTP routes with WebSocket routes
- Trying to use @app.route which is not in FastAPI
Solution
Step 1: Recognize asynchronous WebSocket methods
FastAPI WebSocket methods are async, so you must use await to call them.Step 2: Identify the method to accept a connection
The method to accept a WebSocket connection is accept(), which must be awaited as await websocket.accept().Final Answer:
await websocket.accept() -> Option CQuick Check:
Accept WebSocket connection = await websocket.accept() [OK]
- Forgetting to use await with async methods
- Using websocket.connect() which does not exist
- Calling accept() without await causing runtime errors
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}")Solution
Step 1: Trace the WebSocket message flow
The server accepts the connection, then waits to receive text from the client. It stores the received text in 'data'.Step 2: Understand the response sent back
The server sends back a message with the text 'Message text was: ' plus the received data. If client sends 'hello', the response is 'Message text was: hello'.Final Answer:
Message text was: hello -> Option AQuick Check:
Sent message = 'Message text was: hello' [OK]
- Confusing received message with sent message
- Missing await causing runtime errors
- Assuming server sends back raw client message without prefix
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
websocket.accept()
data = await websocket.receive_text()
await websocket.send_text(data)Solution
Step 1: Check async method calls
In FastAPI, websocket.accept() is an async method and must be awaited.Step 2: Identify missing await
The code calls websocket.accept() without await, which will cause a runtime error.Final Answer:
Missing await before websocket.accept() -> Option BQuick Check:
Async methods require await = missing await [OK]
- Calling async methods without await
- Confusing which methods are async
- Assuming accept() is synchronous
Solution
Step 1: Understand continuous message handling
To handle multiple messages, the server must loop indefinitely, receiving and sending messages repeatedly.Step 2: Check async calls and loop structure
async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data[::-1]) uses an async while True loop, awaits receive_text(), and sends back reversed text with await send_text(), correctly handling async and continuous flow.Final Answer:
async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data[::-1]) -> Option DQuick Check:
Continuous async loop with await calls = async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(data[::-1]) [OK]
- Missing loop for continuous messages
- Not awaiting async methods
- Using for loop incorrectly on async receive_text()
- Calling async methods without await
Ready to prove it?
Pass the test and this pattern moves unknown
