Can the same graphql schema be used across multiple strawberry fastapi routers?

308 views Asked by At

I have strawberry setup to run with fastapi. Basically, like the examples, the fastapi initialization code creates a GraphQLRouter with a Schema object and a context_getter.

Everything works great, I use __get_context to pass some Dependencies in.
What I don't know is, how do I conditionally call Dependencies?

Like I might want a Depends(UserManager) on some graphql calls and Depends(ClientManager) on others. Normally in fast api, I could use different routers to assign different dependencies. But most of the strawberry fastapi examples use a single router for a single schema. Or more rarely multiple routers across multiple schemas.

How do I break up a strawberry GraphQL Schema across multiple GraphQLRouters so I can use different Depends chains for different requests?

1

There are 1 answers

0
Steve On

I haven't toyed with the context dependency values yet, but I did just resolve the issue of multiple graphql routers. There is a merge_types helper method.

You'll need to import the queries and mutations from your respective paths and combine them into a single GraphQLRouter decleration. Here's an example:

from fastapi import FastAPI
from routers route1
from routers import route2
from strawberry import Schema
from strawberry.tools import merge_types
from strawberry.fastapi import GraphQLRouter

app = FastAPI()

route1_schema = route1.schema
route2_schema = route2.schema

query = merge_types("Query", (route1_schema.query, route2_schema.query))

schema = Schema(query=query)
graphql_router = GraphQLRouter(schema=schema)

app.include_router(graphql_router, prefix="/graphql")

Now all your queries will be accessible (provided no naming conflicts) in the same api router. Here's the github issue I found that helped me towards the solution: https://github.com/strawberry-graphql/strawberry/pull/1273