Skip to content

GraphQL

FastAPIでは、Strawberry GraphQLを使用してGraphQL APIを実装できます。

Terminal window
pip install strawberry-graphql[fastapi]
import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
@strawberry.type
class User:
id: int
name: str
email: str
@strawberry.type
class Query:
@strawberry.field
def user(self, id: int) -> User:
return User(id=id, name="John Doe", email="john@example.com")
schema = strawberry.Schema(Query)
graphql_app = GraphQLRouter(schema)
app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")
@strawberry.type
class Mutation:
@strawberry.mutation
def create_user(self, name: str, email: str) -> User:
user = User(id=1, name=name, email=email)
# データベースに保存
return user
schema = strawberry.Schema(Query, Mutation)