Courses 0%
07
Api Protocols and Api Architectures · Chapter 7 of 42

Graph Query Language

Akhil
Akhil Sharma
30 min

Graph Query Language

A query language that lets clients request exactly the data they need in a single request — solving REST's over-fetching and under-fetching problems.

GraphQL:

Ask for Exactly What You Need (The Data Query Revolution)

🎯 Challenge 1: The Restaurant Menu Problem Imagine this scenario: You go to a restaurant and order a burger. But here's the catch:

Option A (Traditional): You get a burger, but it comes with fries, coleslaw, a drink, and dessert - even though you only wanted the burger. You pay for everything and throw away what you don't need.

Option B (Your Choice): You order exactly what you want - just the burger - and pay only for that.

Pause and think: Which option lets you get exactly what you need, nothing more, nothing less?

The Answer: GraphQL is Option B! Traditional REST APIs give you fixed data sets (over-fetching or under-fetching). GraphQL lets you request EXACTLY the data you need!

REST API (Fixed Endpoints):

GET /users/123

json

You only wanted name and email, but got EVERYTHING!

GraphQL (Query What You Need):

json

You asked for name and email, you got ONLY name and email!

Key Insight: GraphQL eliminates over-fetching and under-fetching by letting clients specify exactly what data they need!

📱 Interactive Exercise: The Mobile App Nightmare

Scenario: You're building a social media app. The feed shows posts with:

  • Author name and avatar
  • Post content
  • Like count
  • First 3 comments

REST Approach (The Waterfall):

Step 1: GET /posts

json

Step 2: GET /users/101

json

Step 3: GET /users/102

json

Step 4: GET /posts/1/comments

json

Step 5: GET /posts/2/comments

json

Total: 5 HTTP requests!

😱Network time: 50ms × 5 = 250ms

Battery drain: High

GraphQL Approach (Single Query):

graphql

Total: 1 HTTP request! ✨ Network time: 50ms Battery drain: Low

Real-world parallel: REST is like making multiple trips to different stores (author info store, comments store, etc.). GraphQL is like Amazon - one order, everything delivered together!

The JSON Response:

json

Key Insight: GraphQL solves the N+1 query problem by letting you fetch nested related data in a single request!

🏗️ Building Your First GraphQL API

Step 1: Define the Schema (The Contract)

graphql

Step 2: Implement Resolvers (The Logic)

// resolvers.js

js

Step 3: Set Up the Server

// server.js

js

| Step 4: Make Queries (The Client) // client.js

js

Real-world parallel: Queries are like asking questions (no side effects). Mutations are like giving commands (something changes).

🚨 Common Misconception: "GraphQL Replaces REST Completely... Right?"

You might think: "GraphQL is better, so I should use it for everything!"

The Reality: They serve different purposes!

REST Strengths:

✅ Simple caching (HTTP cache headers work great)

✅ File uploads/downloads (straightforward)

✅ Public APIs (easier for third parties)

✅ Monitoring/logging (standard HTTP tools work)

✅ Learning curve (easier to understand)

GraphQL Strengths:

✅ Flexible data fetching (clients control response shape)

✅ Reducing over-fetching (mobile app efficiency)

✅ Rapid frontend development (no backend changes needed)

✅ Strong typing (schema validation)

✅ Single endpoint (easier versioning)

When REST is Better:

Public API for third-party developers

└─→ REST: Simpler docs, easier integration

File upload service

└─→ REST: Multipart form-data is standard

Simple CRUD operations

└─→ REST: Overkill to use GraphQL

Caching is critical

└─→ REST: HTTP caching is well-understood

When GraphQL is Better:

Complex, nested data requirements

└─→ GraphQL: Fetch everything in one query

Mobile app with bandwidth constraints

└─→ GraphQL: Fetch only what you need

Rapid frontend iteration

└─→ GraphQL: No backend changes for new fields

Multiple clients with different needs

└─→ GraphQL: Each client queries differently

Hybrid Approach (Common in Practice):

Your API Architecture:

├─ GraphQL (Main API)

│ └─ Web app, mobile app queries │

├─ REST endpoints

│ ├─ /upload (file uploads)

│ ├─ /download/:id (file downloads)

│ └─ /webhook (receive webhooks) │

└─ Public REST API (v1)

└─ For third-party developers

Real-world parallel: GraphQL is like a custom meal (you choose ingredients). REST is like a combo meal (predefined, but simple). Use the right tool for the right job!

💡 Advanced Features: Beyond Basic Queries

  1. Aliases (Multiple Queries for Same Field):
graphql
json
  1. Fragments (Reusable Field Sets):
graphql
  1. Variables (Dynamic Values):
graphql
json
  1. Directives (Conditional Logic):
graphql
  1. Pagination (Handling Large Lists):
graphql
graphql

Real-world parallel: These features are like advanced ordering options at a restaurant - aliases (order same dish twice), fragments (combo meals you define), variables (substitutions), directives (only if...), pagination (meal courses).

⚡ Performance: The N+1 Problem and DataLoader

The N+1 Problem:

| // BAD: N+1 queries

js
graphql

Solution: DataLoader (Batching)

js

Total: 2 database queries! ✨

How DataLoader Works:

Without DataLoader:

Post 1 → Get User 101 → DB Query

Post 2 → Get User 102 → DB Query

Post 3 → Get User 103 → DB Query

Total: 3 queries

With DataLoader:

Post 1 → Request User 101 ┐

Post 2 → Request User 102 ├→ DataLoader batches

Post 3 → Request User 103 ┘ ↓

Single DB Query:

sql

Total: 1 query!

Real-world parallel: DataLoader is like carpooling. Instead of each person driving separately (N+1 queries), everyone goes in one car (batched query).

🔐 Authentication & Authorization

| Authentication (Who are you?):

js

Authorization

js
graphql

Real-world parallel: Authentication is like showing your ID at a building entrance (who you are). Authorization is like which floors your keycard can access (what you can do).

🎪 GraphQL vs REST: Real-World Comparison

Scenario: Social Media API

REST Approach:

Endpoints:

├── GET /users/:id

├── GET /users/:id/posts

├── GET /posts/:id

├── GET /posts/:id/comments

├── POST /posts

├── POST /posts/:id/like

├── DELETE /posts/:id

└── ... (50+ endpoints)

Problems:

  1. Over-fetching: GET /users/:id returns too much data

  2. Under-fetching: Need multiple requests for post + comments

  3. Versioning: /v1/users vs /v2/users

  4. Documentation: Must document each endpoint

GraphQL Approach:

Single Endpoint:

bash
graphql

Benefits:

  1. Fetch exactly what you need

  2. Single request for nested data

  3. No versioning needed (evolve schema)

  4. Self-documenting (introspection)

Mobile App Example:

bash

GraphQL (Feed screen):

POST /graphql

{ posts { title author { name avatar } comments(limit: 3) { text } } }

  1. GraphQL Code Generator

Now you have type-safe queries!

  1. GraphQL Federation (Microservices)

Gateway: Combines both services into one schema!

Real-world parallel: These tools are like a fully-equipped kitchen:

  • Playground = Test kitchen (try recipes)
  • Apollo Client = Recipe book (structured cooking)
  • Code Generator = Automated prep work
  • Federation = Multiple chefs working together

💡 Final Synthesis Challenge: The Data Ordering System

Complete this comparison: "REST APIs are like ordering from a fixed menu where each dish comes with predetermined sides. GraphQL is like..."

Your answer should include:

  • Data flexibility
  • Network efficiency
  • Developer experience
  • Type safety

Take a moment to formulate your complete answer...

The Complete Picture: GraphQL is like a build-your-own meal system where:

✅ You specify exactly what ingredients you want (query what you need)

✅ Everything comes in one order (single request for nested data)

✅ The menu is typed and documented (schema introspection)

✅ You can change your order without the kitchen changing recipes (frontend flexibility)

✅ The kitchen optimizes multiple orders together (DataLoader batching)

✅ You only pay for what you ordered (no over-fetching)

✅ Same order form works for everyone (single endpoint)

✅ Changes are backward compatible (schema evolution)

This is why:

  • Facebook invented GraphQL (complex, nested social data)

  • GitHub uses GraphQL API (flexible data access)

  • Shopify uses GraphQL (mobile app efficiency)

  • Netflix experiments with GraphQL (rapid frontend iteration)

GraphQL transforms data fetching from rigid endpoints into flexible, efficient queries!

🎯 Quick Recap: Test Your Understanding Without looking back, can you explain:

  1. What problem does GraphQL solve that REST doesn't?

  2. What's the difference between a Query and a Mutation?

  3. What is the N+1 problem and how does DataLoader solve it?

  4. When should you use REST instead of GraphQL?

Mental check: If you can answer these clearly, you've mastered GraphQL fundamentals!

🚀 Your Next Learning Adventure Now that you understand GraphQL, explore:

Advanced GraphQL:

  • Subscriptions (real-time updates via WebSockets)

  • GraphQL Federation (microservices with unified schema)

  • Custom scalars (Date, JSON, Upload types)

  • Error handling strategies

Performance & Optimization:

  • Query complexity analysis

  • Rate limiting GraphQL APIs

  • Persisted queries (security & caching)

  • APQ (Automatic Persisted Queries)

Related Technologies:

  • Relay (Facebook's GraphQL client)

  • Hasura (Instant GraphQL on databases)

  • Prisma (Database ORM with GraphQL)

  • AppSync (AWS managed GraphQL)

Real-World Case Studies:

  • How GitHub built their GraphQL API

  • Netflix's GraphQL journey

  • Shopify's API evolution to GraphQL

  • Airbnb's GraphQL adoption story


Key Takeaways

  1. GraphQL lets clients request exactly the data they need — no over-fetching or under-fetching like REST
  2. A single endpoint handles all queries and mutations — unlike REST which has multiple endpoints per resource
  3. The schema defines the API contract — strongly typed, self-documenting, and introspectable
  4. N+1 query problems are common in GraphQL — use DataLoader or similar batching to avoid excessive database queries
  5. GraphQL adds complexity over REST — use it when your clients have diverse data needs, not as a default choice
Chapter complete!

Course Complete!

You've finished all 42 chapters of

System Design Indermediate

Browse courses
Up next Protocol Buffers
Continue