GraphQL with FastAPI (Strawberry)

Difficulty: Advanced

Question

Can you use GraphQL with FastAPI? How does it compare to REST?

Answer

Yes - Strawberry is the recommended GraphQL library for FastAPI. It uses Python type hints and dataclasses to define the schema, fitting naturally with FastAPI's type-driven approach.

Strawberry provides a `GraphQLRouter` that mounts directly into FastAPI. It supports queries, mutations, subscriptions, and a built-in GraphiQL IDE.

REST vs GraphQL trade-offs: - GraphQL eliminates over-fetching and under-fetching - clients request exactly the fields they need - REST is simpler, has better caching (HTTP cache), and is more widely understood - GraphQL adds complexity: N+1 queries, schema management, and client tooling - Use GraphQL when clients have diverse data needs; REST for simple CRUD APIs

FastAPI supports both simultaneously - mount GraphQL alongside REST routes.

Code examples

Strawberry GraphQL with FastAPI

import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
from typing import List

@strawberry.type
class User:
    id: int
    name: str
    email: str

users_db = [
    User(id=1, name="Alice", email="alice@example.com"),
    User(id=2, name="Bob", email="bob@example.com"),
]

@strawberry.type
class Query:
    @strawberry.field
    def users(self) -> List[User]:
        return users_db

    @strawberry.field
    def user(self, id: int) -> User | None:
        return next((u for u in users_db if u.id == id), None)

@strawberry.type
class Mutation:
    @strawberry.mutation
    def create_user(self, name: str, email: str) -> User:
        user = User(id=len(users_db) + 1, name=name, email=email)
        users_db.append(user)
        return user

schema = strawberry.Schema(query=Query, mutation=Mutation)
graphql_app = GraphQLRouter(schema)

app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")
# GraphiQL IDE available at /graphql

Key points

Concepts covered

GraphQL, Strawberry, schema, resolvers, REST vs GraphQL