Strawberry GraphQL FastAPI Resolvers
Define a GraphQL schema with Strawberry on FastAPI, writing typed resolvers for queries and mutations with context dependency injection.
Code
import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
BOOKS = {'b-1': {'title': 'Designing Data', 'pages': 320}}
def get_books() -> dict:
return BOOKS
@strawberry.type
class Book:
id: strawberry.ID
title: str
pages: int
@strawberry.type
class Query:
@strawberry.field
def book(self, id: strawberry.ID) -> Book | None:
record = get_books().get(str(id))
if record is None:
return None
return Book(id=id, title=record['title'], pages=record['pages'])
@strawberry.type
class Mutation:
@strawberry.mutation
def add_book(self, title: str, pages: int) -> Book:
new_id = f'b-{len(get_books()) + 1}'
get_books()[new_id] = {'title': title, 'pages': pages}
return Book(id=new_id, title=title, pages=pages)
schema = strawberry.Schema(query=Query, mutation=Mutation)
app = FastAPI()
app.include_router(GraphQLRouter(schema), prefix='/graphql')
# GraphQL 查询示例:
# query { book(id: "b-1") { title pages } }
# mutation { addBook(title: "GraphQL in Prod", pages: 240) { id } }How the snippet works
Strawberry GraphQL FastAPI Resolvers comes down to the classes Book, Query and Mutation and the functions get_books, book and add_book.
From fastapi it pulls FastAPI, GraphQLRouter — the imports name exactly which library surface the snippet touches.
Points of care
fastapiandstrawberrymust be installed first — the snippet imports them directly.
Applying it
The main signature reads def get_books() -> dict
The surface worth importing is get_books; the helpers around it are private to the snippet.
Statements that matter
def book(self, id: strawberry.ID) -> Book | None:
record = get_books().get(str(id))
if record is None:
return None
return Book(id=id, title=record['title'], pages=record['pages'])
return Book(id=id, title=record['title'], pages=record['pages'])
@strawberry.type
class Mutation:
@strawberry.mutation
def add_book(self, title: str, pages: int) -> Book:
new_id = f'b-{len(get_books()) + 1}'
get_books()[new_id] = {'title': title, 'pages': pages}
def add_book(self, title: str, pages: int) -> Book:
new_id = f'b-{len(get_books()) + 1}'
get_books()[new_id] = {'title': title, 'pages': pages}
return Book(id=new_id, title=title, pages=pages)
Interactive Tools for This Topic
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.GraphQL SDL to TypeScript ConverterParse GraphQL SDL type, input, interface, enum, union, and scalar definitions into strict TypeScript interfaces and literal unions locally.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `fastapi` and `strawberry`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.