Defining Types, Queries and Mutations
Build a typed GraphQL schema with Strawberry and mount it on a FastAPI app with shared dependencies.
Why Strawberry for GraphQL on FastAPI
Strawberry is a code-first GraphQL library for Python that uses dataclasses and type hints to define your schema. Instead of writing GraphQL SDL by hand, you write plain Python classes and Strawberry derives the schema from them.
- Code-first: the Python types ARE the source of truth — the SDL is generated.
- Type-safe: standard type hints (
int,str,list[str],Optional) map directly to GraphQL types. - ASGI-native: ships a router that mounts cleanly on a FastAPI app, sharing its event loop and dependency system.
In this lesson we build a typed schema (types, a Query, and a Mutation) and mount it on FastAPI with shared dependencies.
Defining an Object Type
A GraphQL object type is just a class decorated with @strawberry.type. Each annotated attribute becomes a field. Type hints determine the GraphQL field type: int becomes Int, str becomes String, and a non-optional field becomes non-null (!).
- Use
strawberry.IDfor identifier fields — it serializes as a string but signals identity semantics. Optional[...](orX | None) makes a field nullable.
import strawberry
from typing import Optional
@strawberry.type
class Book:
id: strawberry.ID
title: str
author: str
pages: int
summary: Optional[str] = NoneAll lessons in this course
- Defining Types, Queries and Mutations
- Solving N+1 Queries with DataLoaders
- Real-Time GraphQL Subscriptions
- Query Cost Analysis and Depth Limiting