Skip to content
Advertisement

Strawberry+FastAPI: How to get request-info in a dependency?

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?

Advertisement

Answer

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:
    ...

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement