Is it possible to use FastAPI dependencies in a GraphQLApp route?
For example, using the docs:
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
return "Hello " + name
app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))
add_route doesn't really take dependencies, so would the solution be to use middleware to put things into request.state?
Essentially, my goal would be something like
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
return "Hello " + name
app = FastAPI()
@router.get("/gql")
def read_items(request: Request, some_dep = fastapi.Depends()):
request.state.deps = [some_dep]
return GraphQLApp(schema=graphene.Schema(query=Query))(request)
Add any other context or screenshots about the feature request here.
Solved - it appears that the issue was that add_route was a Starlette export rather than FastAPI, thus having no concept of dependencies. The regular decorator syntax works if you use the Graph
import fastapi
import graphene
from starlette.requests import Request
from starlette.graphql import GraphQLApp
router = fastapi.APIRouter()
graphql_app = GraphQLApp(schema=graphene.Schema(query=Query))
class Query(graphene.ObjectType):
hello = graphene.Field(graphene.String, name=graphene.String())
def resolve_hello(root, info, name):
coverage = info.context["request"].state.some_dep
return f"Hello {some_dep.some_method(name)}"
@router.post('/gql')
async def f(request: Request, some_dep=fastapi.Depends()):
request.state.dep = som_dep;
return await graphql_app.handle_graphql(request=request)
Thanks for reporting back and closing the issue :+1:
Its not showing the graphiql ide. {"detail":"Method Not Allowed"}
Most helpful comment
Solved - it appears that the issue was that
add_routewas a Starlette export rather than FastAPI, thus having no concept of dependencies. The regular decorator syntax works if you use the Graph