I am trying to run an strawberry example from this tutorial but it does not work.
I have the code:
from fastapi import FastAPI
import strawberry
from strawberry.fastapi import GraphQL
@strawberry.type
class Book:
title: str
author: str
price: int
@strawberry.type
class Query:
@strawberry.field
def book(self) -> Book:
return Book(title="Computer Fundamentals", author="Sinha", price=300)
schema = strawberry.Schema(query=Query)
graphql_app = GraphQL(schema)
app = FastAPI()
app.add_route("/book", graphql_app)
app.add_websocket_route("/book", graphql_app)
but when I try to run it with uvicorn Mystrawberry:app --reload
it says
ImportError: cannot import name 'GraphQL' from 'strawberry.fastapi'
Now, in the Strawberry documentation examples they use GraphQLRouter rather than GraphQL, and I don't know if that is an old version or a typo.
It would seem your tutorial is incorrect or out of date. Take a look at the official documentation, it seems like the way to do it is to do
from strawberry.fastapi import GraphQLRouter
, and include that router in your FastAPI application.