Strawberry GraphQL FastAPI Resolvers

Define a GraphQL schema with Strawberry on FastAPI, writing typed resolvers for queries and mutations with context dependency injection.

PythonFastapiData Fetching

Code

pythonsnippet
45 lines
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

  • fastapi and strawberry must 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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `fastapi` and `strawberry`, which the package manager must provide.