Problem combining FastAPI dependency and Strawberry GraphQL context

1.6k views Asked by At

I am struggling to get a certain type of dependency to work with FastAPI and Strawberry GraphQL, specifically with establishing a context. My service contains both a GraphQL route and other types of routes and the following works just fine:

@router.get("/identity", response_model=str)
async def user(user_info: str = Depends(get_current_user)):
    return user_info

but on my GraphQL side, I have

async def get_context(user=Depends(get_current_user())):
    log.info(user)
    return {"user": user}

graphql_app = GraphQLRouter(schema, graphiql=True, context_getter=get_context)

when I test this, get_current_user() is not getting invoked, and the value of user is output in the above logging as <inspect._empty object at ...>.

Why would the dependency not get handled in this case?

1

There are 1 answers

1
M.O. On BEST ANSWER

It looks like in your definition of get_context, you are calling get_current_user, but in Depends, you must pass the function itself, not its return value (you're doing this correctly in your user function). Changing your function definition to

async def get_context(user=Depends(get_current_user)):

should do the trick.