GraphQL is the API query language that lets clients request exactly the data they need. In 2026, GraphQL is used by Facebook, GitHub, Shopify, Twitter, and thousands of startups. This guide covers GraphQL schema design, queries, mutations, subscriptions, and production patterns.
📋 Table of Contents
GraphQL vs REST
| Aspect | REST | GraphQL |
|---|---|---|
| Data fetching | Multiple endpoints, fixed response | Single endpoint, flexible response |
| Over-fetching | Common problem | Eliminated — get exactly what you need |
| Under-fetching | Multiple requests needed | One request for nested data |
| Type safety | OpenAPI (optional) | Built-in strong typing |
| Learning curve | Low | Medium |
| Best for | Simple CRUD APIs | Complex, interconnected data |
GraphQL Schema
# Schema Definition Language (SDL)
type Query {
user(id: ID!): User
users(first: Int, after: String): UserConnection!
post(id: ID!): Post
posts(filter: PostFilter, orderBy: PostOrderBy): [Post!]!
me: User
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): Boolean!
createPost(input: CreatePostInput!): Post!
}
type Subscription {
userCreated: User!
postPublished: Post!
}
type User {
id: ID!
name: String!
email: String!
posts(first: Int): [Post!]!
createdAt: DateTime!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
tags: [String!]!
published: Boolean!
publishedAt: DateTime
}
input CreateUserInput {
name: String!
email: String!
password: String!
}
type CreateUserPayload {
user: User!
token: String!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
scalar DateTime
Queries and Mutations
# Basic query
query GetUser {
user(id: "1") {
id
name
email
posts(first: 5) {
title
publishedAt
}
}
}
# Query with variables (best practice)
query GetUserPosts($userId: ID!, $first: Int = 10) {
user(id: $userId) {
name
posts(first: $first) {
id
title
tags
author {
name
}
}
}
}
# Mutation
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
author {
name
}
publishedAt
}
}
# Variables JSON:
# {
# "input": {
# "title": "TypeScript Guide 2026",
# "content": "...",
# "tags": ["typescript", "javascript"]
# }
# }
# Fragments — reuse field selections
fragment UserFields on User {
id
name
email
}
query {
user(id: "1") { ...UserFields }
me { ...UserFields }
}
GraphQL with Python (Strawberry)
pip install strawberry-graphql fastapi uvicorn
import strawberry
from strawberry.fastapi import GraphQLRouter
from fastapi import FastAPI
from typing import Optional
import asyncio
@strawberry.type
class User:
id: strawberry.ID
name: str
email: str
@strawberry.type
class Post:
id: strawberry.ID
title: str
content: str
author: User
@strawberry.input
class CreatePostInput:
title: str
content: str
tags: list[str] = strawberry.field(default_factory=list)
@strawberry.type
class Query:
@strawberry.field
async def user(self, id: strawberry.ID) -> Optional[User]:
# Fetch from database
user_data = await db.users.find_one({"id": id})
if not user_data:
return None
return User(id=user_data["id"], name=user_data["name"], email=user_data["email"])
@strawberry.field
async def posts(self, first: int = 10) -> list[Post]:
posts_data = await db.posts.find().limit(first).to_list(first)
return [Post(id=p["id"], title=p["title"], content=p["content"],
author=User(id=p["author_id"], name=p["author_name"], email=""))
for p in posts_data]
@strawberry.type
class Mutation:
@strawberry.mutation
async def create_post(self, input: CreatePostInput) -> Post:
new_post = {"title": input.title, "content": input.content, "tags": input.tags}
result = await db.posts.insert_one(new_post)
return Post(id=str(result.inserted_id), title=input.title, content=input.content,
author=User(id="1", name="Alice", email="alice@example.com"))
schema = strawberry.Schema(query=Query, mutation=Mutation)
graphql_app = GraphQLRouter(schema)
app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")
# Playground at http://localhost:8000/graphql
N+1 Problem and DataLoader
The N+1 problem: fetching a list of posts, then making 1 DB query per post to get its author = N+1 queries total.
from strawberry.dataloader import DataLoader
async def load_users_by_ids(user_ids: list[str]) -> list[User]:
# ONE query for all user IDs
users_data = await db.users.find({"id": {"$in": user_ids}}).to_list(None)
user_map = {u["id"]: u for u in users_data}
return [user_map.get(uid) for uid in user_ids]
# In your GraphQL context
context = {
"user_loader": DataLoader(load_fn=load_users_by_ids)
}
# In resolver — batches all user lookups into one query
@strawberry.type
class Post:
author_id: strawberry.Private[str]
@strawberry.field
async def author(self, info: strawberry.types.Info) -> User:
return await info.context["user_loader"].load(self.author_id)
Apollo Client (React)
// Setup
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery, useMutation } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache(),
});
// Wrap app
function App() {
return <ApolloProvider client={client}><Router /></ApolloProvider>;
}
// Query hook
const GET_POSTS = gql`
query GetPosts($first: Int!) {
posts(first: $first) {
id title author { name }
}
}
`;
function PostList() {
const { data, loading, error } = useQuery(GET_POSTS, {
variables: { first: 10 },
fetchPolicy: 'cache-and-network',
});
if (loading) return <Spinner />;
if (error) return <Error message={error.message} />;
return (
<ul>
{data.posts.map(post => (
<li key={post.id}>{post.title} by {post.author.name}</li>
))}
</ul>
);
}
// Mutation hook
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) { id title }
}
`;
function NewPostForm() {
const [createPost, { loading }] = useMutation(CREATE_POST, {
update(cache, { data: { createPost } }) {
// Update cache to include new post
cache.modify({
fields: {
posts(existingPosts = []) {
return [...existingPosts, createPost];
}
}
});
}
});
const handleSubmit = (title: string) => {
createPost({ variables: { input: { title, content: '' } } });
};
}
GraphQL in 2026 is mature and production-ready. Use it when your frontend needs flexible data fetching, when mobile and web clients need different data shapes, or when you have interconnected data (users/posts/comments). Use REST for simple CRUD APIs or when clients don’t control what data they receive.
📚 You might also like
🔗 Share this article




✍️ Leave a Comment