2

Consider this code:

import strawberry

from fastapi import FastAPI, Depends, Request, WebSocket, BackgroundTasks
from strawberry.types import Info
from strawberry.fastapi import GraphQLRouter


def custom_context_dependency() -> str:
    # ===> need to get request here, to get request header
    return "John"

def has_root_access() -> bool:
    # ===> need to get request and header to get user info
    #      and user permissions
    return False

async def get_context(
    custom_value=Depends(custom_context_dependency),
    has_root_access=Depends(has_root_access),
):
    return {
        "custom_value": custom_value,
        "has_root_access": has_root_access,
    }


@strawberry.type
class Query:
    @strawberry.field
    def example(self, info: Info) -> str:
        return f"Hello {info.context['custom_value']}"

schema = strawberry.Schema(Query)
graphql_app = GraphQLRouter(
  schema,
  context_getter=get_context,
)

app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")

How do I get the request info in the dependencies custom_context_dependency and has_root_access?

npk
  • 1,512
  • 1
  • 13
  • 26
  • 2
    In plain FastAPI you can add a parameter typed as `Request` to your dependency and it'll automagically be filled. Since it seems strawberry can use the same Dependency system (with Depends being filled) through FastAPI, I'm guessing you can just add the parameter: `def custom_context_dependency(request: Request) -> str:` – MatsLindh Sep 08 '22 at 19:08
  • It works! But request is not always supplied. I'll add an answer – npk Sep 09 '22 at 05:32

1 Answers1

1

When I tried FastAPI's Request, it was still showing some error when Strawberry's page was opened. Later I understood that the error was being raised by WebSocket connection. So my solution was to make request and web-socket optional params:

def custom_context_dependency(
    request: Request = None,
    websocket: WebSocket = None,
) -> str:
    item = request or websocket
    ...
    return "John"

Either request or websocket will be present for every request.

To get a header specifically, FastAPI's Header is also supported.

def custom_context_dependency(
    Authorization: str = Header(None)
) -> str:
    ...
npk
  • 1,512
  • 1
  • 13
  • 26