fastapi icon indicating copy to clipboard operation
fastapi copied to clipboard

Is there a way to pass FastAPI dependencies to a GraphQL App?

Open mmartinsky opened this issue 6 years ago • 11 comments

First check

  • [x] 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.
  • [x] 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.

mmartinsky avatar Apr 16 '20 17:04 mmartinsky

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)

mmartinsky avatar Apr 22 '20 17:04 mmartinsky

Thanks for reporting back and closing the issue :+1:

tiangolo avatar Apr 25 '20 18:04 tiangolo

Its not showing the graphiql ide. {"detail":"Method Not Allowed"}

silicology1 avatar Dec 06 '20 15:12 silicology1

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)

Tushant avatar Jul 09 '21 03:07 Tushant

@Tushant interesting, trying to solve the same thing myself. would love to see an example that works with the imports...what is URL() and GraphQLContext?

Nogbit avatar Jul 26 '21 23:07 Nogbit

@Nogbit its a datastructure from starlette which you can explore here https://github.com/encode/starlette/blob/master/starlette/datastructures.py

from starlette.datastructures import URL

GraphQlContext is the type-hints which is a dictionary where string key can be of anything. This is what my GraphQlContext looks like

from typing import Any, Dict

from sqlalchemy.orm import Session
from starlette.requests import Request

GraphQLContext = Dict[str, Any]


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

I hope this helps you.

Tushant avatar Jul 27 '21 06:07 Tushant

@Tushant thanks that helps, I did manage to whip this up yesterday. Our solutions seem better than simply mounting Ariadne as a sub app which is nice.

from ariadne import QueryType, make_executable_schema
from ariadne import graphql
from ariadne.constants import PLAYGROUND_HTML

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse

app = FastAPI()

# Most basic of GraphQL schema
type_defs = """
    type Query {
        hello: String!
    }
"""

query = QueryType()


@query.field("hello")
async def resolve_hello(*_):
    return('hello world')


schema = make_executable_schema(type_defs, query)


@app.get("/graphql", response_class=HTMLResponse)
async def graphql_get(request: Request):
    return PLAYGROUND_HTML


@app.post("/graphql")
async def graphql_post(request: Request):
    data = await request.json()

    # https://ariadnegraphql.org/docs/api-reference#graphql
    return await graphql(schema, data)

Nogbit avatar Jul 27 '21 15:07 Nogbit

My issue is passing dependencies to the resolvers. So I have the following, based on your advice:

app = FastAPI(root_path="/graphql")

async def get_graphql_context(request: Request,) -> Dict[str, Any]:
    return {"request": request}

async def resolve_graphql_context(request: Request) -> Dict[str, Any]:
    return await get_graphql_context(request)

type_definitions = load_schema_from_path("./schemas")
schema = make_executable_schema(type_definitions, [query])

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


@app.get(
    BASE.route,
    tags=["GraphQL"],
    response_model=HTMLResponse,
    summary="Get the GraphQL Playground",
    description="Get the GraphQL Playground",
)
async def graphql_playground(request: Request):
    # request._url = URL("/graphql")
    return await graphql.render_playground(request=request)


@app.post(
    BASE.route,
    tags=["GraphQL"],
    response_model=GraphQLResult,
    summary="Query the GraphQL endpoint",
    description="Query the GraphQL endpoint",
)
async def graphql_post(
    request: Request,
    elasticsearch_client: ElasticsearchDslClient = strict_security(
        get_elasticsearch_client, scopes=BASE.scopes.post
    ),
) -> Response:
    return await graphql.graphql_http_server(request=request)

But how do I get the dependencies to the resolvers (e.g. I have a query resolver in another file which I added to make_executable_schema)

dirkbrnd avatar Jul 28 '21 13:07 dirkbrnd

You can use graphql(schema, data, context_value=custom_context) instead and pass the context in that call. So you can inject whatever you want in the context. If you need to inject dependencies only on specific resolvers I would go with a DI library like https://python-dependency-injector.ets-labs.org/examples/index.html

sebastiandev avatar Nov 25 '21 14:11 sebastiandev

Does anyone have an example of this utilizing it for auth0 verification?

ChuksGrinage avatar Dec 12 '21 18:12 ChuksGrinage

I don't hink you need that since the request will always be added to the GraphQL context, so you can access the auth token from it in your middlewares or wherever you are using them.

Still, you can go the FastAPI way using dependency injection to get the token header and adding that to the context.


async def build_graphql_context(request: Request, authorization: str):
    return tools.DictObject(
        req=request,
        authorization=authorization,
    )

@app.post("/graphql")
async def graphql(request: Request, authorization: str = Header(None)):
    request_data = dict(request)
    ctx = await build_graphql_context(request, authorization)
    success, response = await gql_app.execute(request, context=ctx)
    return JSONResponse(content=response, status_code=200 if success else 400)

Our GraphQL App for Ariadne looks like this

import json
import typing

from ariadne import graphql, load_schema_from_path, make_executable_schema, snake_case_fallback_resolvers
from ariadne.constants import PLAYGROUND_HTML
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse


class GraphQLApp:
    def __init__(
        self,
        app,
        schema_path: str,
        error_coercer: typing.Callable = None,
        types: list = None,
        query=None,
        mutation=None,
    ):
        schema_path = schema_path
        type_defs = load_schema_from_path(schema_path)
        types = types or []
        self.error_coercer = error_coercer
        self.schema = make_executable_schema(
            type_defs,
            *types,
            query,
            mutation,
            snake_case_fallback_resolvers,
        )

    async def render_playground(self):
        return PLAYGROUND_HTML

    async def execute(self, request: Request, context: dict = None):
        # https://ariadnegraphql.org/docs/api-reference#graphql
        context = context or dict(request=request)
        req_data = await request.json()
        return await graphql(self.schema, req_data, context_value=context, error_formatter=self.error_coercer)

sebastiandev avatar Dec 14 '21 13:12 sebastiandev