pythongraphqlfastapistrawberry-graphql

Fastapi + Strawberry GraphQL


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.


Solution

  • This has been documented here: https://strawberry.rocks/docs/integrations/fastapi#fastapi

    From the docs

    import strawberry
    
    from fastapi import FastAPI
    from strawberry.fastapi import GraphQLRouter
    
    
    @strawberry.type
    class Query:
        @strawberry.field
        def hello(self) -> str:
            return "Hello World"
    
    
    schema = strawberry.Schema(Query)
    
    
    graphql_app = GraphQLRouter(schema)
    
    
    app = FastAPI()
    app.include_router(graphql_app, prefix="/graphql")