GraphQL
GraphQL
Section titled “GraphQL”FastAPIでは、Strawberry GraphQLを使用してGraphQL APIを実装できます。
Strawberry GraphQLの設定
Section titled “Strawberry GraphQLの設定”依存関係の追加
Section titled “依存関係の追加”pip install strawberry-graphql[fastapi]基本的な実装
Section titled “基本的な実装”import strawberryfrom fastapi import FastAPIfrom strawberry.fastapi import GraphQLRouter
@strawberry.typeclass User: id: int name: str email: str
@strawberry.typeclass 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")ミューテーション
Section titled “ミューテーション”@strawberry.typeclass 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)