0Pricing
FastAPI Backend Development Bootcamp · Lesson

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.ID for identifier fields — it serializes as a string but signals identity semantics.
  • Optional[...] (or X | 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] = None

All lessons in this course

  1. Defining Types, Queries and Mutations
  2. Solving N+1 Queries with DataLoaders
  3. Real-Time GraphQL Subscriptions
  4. Query Cost Analysis and Depth Limiting
← Back to FastAPI Backend Development Bootcamp