python --version
pip install "strawberry-graphql[fastapi]" uvicorn
Create a GraphQL API with queries, mutations, and field resolvers using Strawberry (Python code-first GraphQL library).
1 from typing import Optional 2 import strawberry 3 from strawberry.fastapi import GraphQLRouter 4 from fastapi import FastAPI 5 6 # In-memory store 7 users_db: dict[int, dict] = {1: {"id": 1, "name": "Alice", "email": "alice@example.com"}} 8 posts_db: list[dict] = [{"id": 1, "title": "Hello GraphQL", "author_id": 1}] 9 10 @strawberry.type 11 class User: 12 id: strawberry.ID 13 name: str 14 email: str 15 16 @strawberry.field 17 def posts(self) -> list["Post"]: 18 return [Post(**p) for p in posts_db if p["author_id"] == int(self.id)] 19 20 @strawberry.type 21 class Post: 22 id: strawberry.ID 23 title: str 24 author_id: int 25 26 @strawberry.field 27 def author(self) -> Optional[User]: 28 user = users_db.get(self.author_id) 29 return User(**user) if user else None 30 31 @strawberry.type 32 class Query: 33 @strawberry.field 34 def get_user(self, user_id: strawberry.ID) -> Optional[User]: 35 user = users_db.get(int(user_id)) 36 return User(**user) if user else None 37 38 @strawberry.field 39 def list_posts(self) -> list[Post]: 40 return [Post(**p) for p in posts_db] 41 42 @strawberry.type 43 class Mutation: 44 @strawberry.mutation 45 def create_post(self, title: str, author_id: int) -> Post: 46 post = {"id": len(posts_db) + 1, "title": title, "author_id": author_id} 47 posts_db.append(post) 48 return Post(**post) 49 50 schema = strawberry.Schema(query=Query, mutation=Mutation) 51 graphql_app = GraphQLRouter(schema) 52 53 app = FastAPI() 54 app.include_router(graphql_app, prefix="/graphql") 55
Sign in to share your feedback and join the discussion.