FastAPI dependencies and websocket #9894
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, WebSocket, Request, Depends
async def my_context_dependency(request: Request):
# Do something with request...
pass
app = FastAPI(dependencies=[Depends(my_context_dependency)])
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
passDescription% websocat ws://127.0.0.1:8000/ws Error: Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.100.0 Python Version3.11.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
|
Beta Was this translation helpful? Give feedback.
-
|
I think I asked the same question recently - intility/fastapi-azure-auth#155. Perhaps someone can look at it? |
Beta Was this translation helpful? Give feedback.
-
|
FastAPI relies on type annotations to inject instances of To fix this you can change the type annotation to async def my_context_dependency(request: HTTPConnection):
if isinstance(request, Request):
# Do something with request...
pass |
Beta Was this translation helpful? Give feedback.
FastAPI relies on type annotations to inject instances of
ResponseorWebSocket.Since
WebSocketis not a subclass ofResponseand there is noRequestin websocket paths, it fails to inject it.To fix this you can change the type annotation to
HTTPConnectionthat is a common ancestor ofResponseandWebSocket: