Skip to main content

🎯 GraphQL

Order exactly what you want, nothing more

The Restaurant Menu Analogy

Two restaurants:

Fixed menu (REST):

  • Order "Combo #3"
  • Get: burger, fries, drink, salad, dessert
  • You maybe just wanted burger and fries
  • Pay for everything anyway

Custom order (GraphQL):

  • "I want burger with extra cheese, and just fries"
  • Get exactly that
  • No waste!

GraphQL lets you ask for exactly what you need.


What Is GraphQL?

GraphQL = Query language for APIs

You describe what data you want.
Server returns exactly that.

Not a database.
Not a protocol.
A query language that sits on your API.

The Core Difference

REST: Multiple endpoints, fixed responses
  /users/123
  /users/123/posts
  /users/123/followers

GraphQL: One endpoint, flexible queries
  POST /graphql
  "Give me user 123's name and their last 5 posts"

How It Works

The Query

Ask for what you need:

query {
  user(id: "123") {
    name
    email
    posts(last: 5) {
      title
      publishedAt
    }
  }
}

Hierarchical structure.
Matches the response shape.

The Response

Get exactly what you asked for:

{
  "data": {
    "user": {
      "name": "Alice",
      "email": "alice@example.com",
      "posts": [
        { "title": "Hello World", "publishedAt": "YYYY-MM-DD" },
        { "title": "GraphQL Tips", "publishedAt": "YYYY-MM-DD" }
      ]
    }
  }
}

No over-fetching. No under-fetching.

Operations

Query (Read)

Get data. Like GET in REST.

query {
  users {
    name
  }
}

Read-focused. Typically no side effects.

Mutation (Write)

Change data. Like POST/PUT/DELETE.

mutation {
  createUser(name: "Bob", email: "bob@example.com") {
    id
    name
  }
}

Creates/updates/deletes.
Returns affected data.

Subscription (Real-time)

Live updates. WebSocket-based.

subscription {
  newMessage(roomId: "123") {
    content
    sender {
      name
    }
  }
}

Push updates when data changes.

Schema

The Type System

GraphQL has a typed schema.
Defines what's queryable.

type User {
  id: ID!
  name: String!
  email: String
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  author: User!
}

! means non-nullable.
[Type] means array.

Introspection

Query the schema itself!

{
  __schema {
    types {
      name
    }
  }
}

Self-documenting. Tools can discover API.

GraphQL vs REST

AspectRESTGraphQL
EndpointsManyOne
Data fetchingFixed responsesFlexible queries
Over-fetchingCommonAvoided
Under-fetchingCommonAvoided
VersioningURL versioningEvolve schema
TypingOptionalRequired
CachingHTTP built-inMore complex

Benefits

1. No Over-fetching

REST: Get user → All 50 fields returned
GraphQL: Get user → Just name and email

Mobile app with slow connection?
Often fetch what you need.

2. No Under-fetching

REST: Get user, then their posts, then each post's comments
  3 round trips!

GraphQL: Get user with posts and comments
  1 request, all nested data.

3. Self-Documenting

Schema IS the documentation.
Tools like GraphiQL show all available queries.
Type safety built in.

4. Frontend Independence

Backend exposes capabilities.
Frontend decides what to fetch.
No waiting for new endpoints.

Challenges

1. Complexity

More setup than REST.
Learning curve.
Tooling required.

2. Caching

REST: GET /users/123 → HTTP cache
GraphQL: POST /graphql → Need custom caching

Solutions: Apollo cache, persisted queries.

3. N+1 Problem

Query users with posts.
Naive implementation:
  1 query for users
  N queries for each user's posts

Solution: DataLoader, batching.

4. Security

Client controls the query.
Deeply nested queries = expensive!

Solutions: Query complexity limits, depth limits.

Common Tools

ToolPurpose
ApolloFull-stack GraphQL platform
GraphiQLIn-browser GraphQL IDE
RelayFacebook's GraphQL client
HasuraInstant GraphQL on databases
PrismaDatabase toolkit with GraphQL

When to Use GraphQL

Good Fit

âś“ Multiple clients (web, mobile, etc.)
âś“ Complex, nested data
âś“ Rapidly evolving frontend
âś“ Need for real-time subscriptions
âś“ Team with GraphQL experience

Maybe Not

âś— Simple CRUD APIs
âś— File uploads (tricky)
âś— Caching is critical
âś— Team unfamiliar with GraphQL
âś— Public APIs for third parties (REST often simpler)

Common Mistakes

1. One Giant Query

Fetching entire app state in one query.
Slow, hard to cache.

Break into logical, reusable queries.

2. No Query Limits

Malicious query:
  users { posts { comments { author { posts { ... }}}}}

Set depth and complexity limits!

3. Ignoring N+1

1000 users, each with posts.
1001 database queries!

Use DataLoader for batching.

FAQ

Q: Does GraphQL replace REST?

Not necessarily. Different tools for different needs. Many use both.

Q: How does GraphQL performance compare to REST?

Not inherently. Fewer requests can mean faster total time. But complex queries can be slow.

Q: Database required?

No! GraphQL can wrap any data source: REST APIs, databases, microservices.

Q: How do I start?

Try Apollo Server (Node.js), Strawberry (Python), or Hasura (instant GraphQL).


Summary

GraphQL is a query language that lets clients request exactly the data they need in a single request.

Key Takeaways:

  • Ask for exactly what you need
  • One endpoint, flexible queries
  • Typed schema is self-documenting
  • Queries (read), Mutations (write), Subscriptions (real-time)
  • Solves over-fetching and under-fetching
  • Caching and security need attention

GraphQL: The data you want, nothing more!

Related Concepts

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.