question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Is there a way to pass FastAPI dependencies to a GraphQL App?

See original GitHub issue

First check

  • I used the GitHub search to find a similar issue and didn’t find it.
  • [x ] I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.

Description

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)

Additional context

Add any other context or screenshots about the feature request here.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

15reactions
mmartinskycommented, Apr 22, 2020

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)
4reactions
Tushantcommented, Jul 9, 2021

Commenting in a hope that it might help if someone encountered issue while using ariadne as a graphql stack

app = FastAPI()


async def get_graphql_context(request: Request, db: Session) -> GraphQLContext:
    return {"request": request, "db": db}

async def resolve_graphql_context(request: Request) -> GraphQLContext:
    return await get_graphql_context(request, request["state"]["db"])


# settings.debug should be used
graphql = GraphQL(schema, debug=True, context_value=resolve_graphql_context)

# app.mount("/graphql/", graphql)


@app.get("/graphql")
async def graphiql(request: Request):
    request._url = URL("/graphql")
    return await graphql.render_playground(request=request)


@app.post("/graphql")
async def graphql_post(request: Request, db: Session = Depends(get_db)):
    request.state.db = db
    return await graphql.graphql_http_server(request=request)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependencies - First Steps - FastAPI - tiangolo
With the Dependency Injection system, you can also tell FastAPI that your path operation function also "depends" on something else that should be...
Read more >
Advanced Dependencies - FastAPI
In Python there's a way to make an instance of a class a "callable". ... sub-dependencies, and this is what will be called...
Read more >
Testing Dependencies with Overrides - FastAPI
In this case, you can override the dependency that calls that provider, and use a custom dependency that returns a mock user, only...
Read more >
Sub-dependencies - FastAPI
It declares an optional query parameter q as a str , and then it just returns it. This is quite simple (not very...
Read more >
Classes as Dependencies - FastAPI
If you pass a "callable" as a dependency in FastAPI, it will analyze the parameters for that "callable", and process them in the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found