Consider this code:
JavaScript
x
41
41
1
import strawberry
2
3
from fastapi import FastAPI, Depends, Request, WebSocket, BackgroundTasks
4
from strawberry.types import Info
5
from strawberry.fastapi import GraphQLRouter
6
7
8
def custom_context_dependency() -> str:
9
# ===> need to get request here, to get request header
10
return "John"
11
12
def has_root_access() -> bool:
13
# ===> need to get request and header to get user info
14
# and user permissions
15
return False
16
17
async def get_context(
18
custom_value=Depends(custom_context_dependency),
19
has_root_access=Depends(has_root_access),
20
):
21
return {
22
"custom_value": custom_value,
23
"has_root_access": has_root_access,
24
}
25
26
27
@strawberry.type
28
class Query:
29
@strawberry.field
30
def example(self, info: Info) -> str:
31
return f"Hello {info.context['custom_value']}"
32
33
schema = strawberry.Schema(Query)
34
graphql_app = GraphQLRouter(
35
schema,
36
context_getter=get_context,
37
)
38
39
app = FastAPI()
40
app.include_router(graphql_app, prefix="/graphql")
41
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:
JavaScript
1
8
1
def custom_context_dependency(
2
request: Request = None,
3
websocket: WebSocket = None,
4
) -> str:
5
item = request or websocket
6
7
return "John"
8
Either request or websocket will be present for every request.
To get a header specifically, FastAPI’s Header
is also supported.
JavaScript
1
5
1
def custom_context_dependency(
2
Authorization: str = Header(None)
3
) -> str:
4
5