Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Dependencies not working on websocket connection #4957

@bgorzsony

Description

@bgorzsony

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import Depends, FastAPI,APIRouter,Request, WebSocket



def my_dependency(request: Request):
    print("called_my_dependency")
    request.state.my_var = "my_var"


app = FastAPI(
    dependencies=[Depends(my_dependency)]
)

def get_test(request: Request):
    print(request.state.my_var)
    return request.state.my_var

async def ws_test(websocket: WebSocket):
    print(websocket.state.my_var)



app.add_api_route('/get',get_test)
app.add_api_websocket_route('/ws',ws_test)

Description

Running the code above and sending a get request to /get yields:

$ curl 127.0.0.1:8000/get | jq
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     8  100     8    0     0   4672      0 --:--:-- --:--:-- --:--:--  8000
"my_var"

It works fine my_dependency function runs

Trying to connect to /ws endpoint on the other hand throws an error:

$ wscat --connect 127.0.0.1:8000/ws
error: Unexpected server response: 500

From the server's output it's visible my_var can't be found because my_dependency doesn't run.

AttributeError: 'State' object has no attribute 'my_var'

I don't know if it's intended or a bug but, I would expect it to run on the websocket connection as well and be able to access the state variables on the request.

I have also tried it with APIRouter and the results are the same.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.78.0

Python Version

Python 3.10.4

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions