Using GraphQL
GraphQL lets clients request exactly the fields they need in a single query, instead of over- or under-fetching through fixed REST endpoints. FastAPI hosts GraphQL services cleanly: the popular strawberry-graphql library (and Ariadne) build apps that integrate with FastAPI's routing, dependencies, and auth.
Setting Up strawberry-graphql
pip install "strawberry-graphql[fastapi]"
import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
class User:
id: int
name: str
email: str
@strawberry.type
class Query:
@strawberry.field
def user(self, id: int) -> User:
return User(id=id, name="Ada", email="[email protected]")
schema = strawberry.Schema(query=Query)
graphql_app = GraphQLRouter(schema)
app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")
Query it:
curl -X POST http://127.0.0.1:8000/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ user(id: 1) { id name } }"}'
# {"data":{"user":{"id":1,"name":"Ada"}}
Notice the client asked for id and name only - email was never sent. That precise field selection is GraphQL's core value.
Mutations
@strawberry.type
class CreateUserInput:
name: str
email: str
@strawberry.type
class Mutation:
@strawberry.mutation
def create_user(self, data: CreateUserInput) -> User:
return User(id=1, name=data.name, email=data.email)
schema = strawberry.Schema(query=Query, mutation=Mutation)
Integrating with the Rest of the App
- Run FastAPI middleware (auth, CORS, logging) around the GraphQL router - it is a normal mounted router.
- Use FastAPI dependencies on context if your resolvers need the request or a database session.
- Keep REST endpoints for simple, cache-friendly reads; use GraphQL for complex, client-driven shapes.
When GraphQL Is the Right Call
Prefer GraphQL when you have multiple heterogeneous clients (web, mobile, third parties) with different field needs, or when REST over-fetching is a measurable problem. For a single internal service with a stable API, REST remains simpler.
Summary
Host GraphQL in FastAPI with strawberry-graphql: define Query and Mutation types, build a schema, and include the GraphQLRouter at a /graphql prefix. Clients select exact fields per request, and the router sits inside FastAPI so your middleware, auth, and deployment story stay unchanged.