import strawberry
from typing import List, Optional
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
@strawberry.type
class User:
id: strawberry.ID
username: str
email: str
posts: List['Post']
@strawberry.type
class Post:
id: strawberry.ID
content: str
author: User
@strawberry.type
class Query:
users: List[User]
posts: List[Post]
@strawberry.type
class Mutation:
@strawberry.mutation
def create_user(self, username: str, email: str) -> User:
new_user = User(id=str(len(users) + 1), username=username, email=email, posts=[])
users.append(new_user)
return new_user
@strawberry.mutation
def create_post(self, content: str, author_id: strawberry.ID) -> Post:
author = next(user for user in users if user.id == author_id)
new_post = Post(id=str(len(posts) + 1), content=content, author=author)
posts.append(new_post)
author.posts.append(new_post)
return new_post
schema = strawberry.Schema(query=Query, mutation=Mutation)
app = FastAPI()
graphql_app = GraphQLRouter(schema)
app.include_router(graphql_app, prefix="/graphql")
# Sample data
users = [
User(id="1", username="alice", email="alice@example.com", posts=[]),
User(id="2", username="bob", email="bob@example.com", posts=[]),
]
posts = []