Fastapi + Strawberry GraphQL

Viewed 2203

I'm currently building a microservice with fastapi.

I want to expose my underlying data via graphql on an additional route. Direct integration from starlette has been deprecated so I tried to use one of the recommended packages strawberry. At the moment, it seems impossible to use in combination with grapqhl.

Example

my_grapqhql.py

from typing import List
import strawberry

@strawberry.type
class Book:
    title: str
    author: str

@strawberry.type
class Query:
    books: List[Book]

schema = strawberry.Schema(query=Query)

What I tried

In the fastapi documentation, asgi components are added like so:

main.py

from fastapi import FastAPI
from strawberry.asgi import GraphQL
from .my_graphql.py import schema

app = FastAPI()
app.add_middleware(GraphQL, schema=schema)

Unfortunately this doesn't work:

TypeError: __init__() got an unexpected keyword argument 'app'

when I switch the last line to mount a module is atleast starts:

app.mount("/graphql", GraphQL(schema))

but the route doesn't load.

2 Answers

This is going to me documented soon: https://github.com/strawberry-graphql/strawberry/pull/1043

To use Strawberry and FastAPI you can do the following:

from fastapi import FastAPI
from strawberry.asgi import GraphQL
from api.schema import Schema

graphql_app = GraphQL(schema)

app = FastAPI()
app.add_route("/graphql", graphql_app)

The new way of adding Strawberry with FastApi which is in documentation also

app = FastAPI()
schema = strawberry.Schema(query=Query,mutation=Mutation,config=StrawberryConfig(auto_camel_case=True))
graphql_app = GraphQLRouter(schema)
app.include_router(graphql_app, prefix="/graphql")
Related