Skip to solution
mediumSystem Design

What is the difference between REST and GraphQL?

1.1k views
01

Understand the problem

Compare API styles.

apirest
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

REST vs. GraphQL: What Is the Difference?

Target Audience: Junior & Senior Software Engineers preparing for System Design Interviews — no prior system design knowledge assumed. Difficulty: Easy to Medium

How to read this doc: Every concept is explained in plain language first. Right after, you'll see

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

REST: assemble from several endpoints
Run Playground
// REST: a screen needs data from multiple endpoints (N round trips)
const user   = await fetch('/api/users/42').then(r => r.json());
const orders = await fetch('/api/users/42/orders').then(r => r.json());
const items  = await fetch('/api/orders/' + orders[0].id + '/items').then(r => r.json());
GraphQL: one query, exact shape
# One request; the server returns exactly this shape, in one round trip.
query {
  user(id: 42) {
    name
    orders(first: 1) {
      id
      items { sku, qty }
    }
  }
}
REST vs GraphQL: counting round trips for the same profile page
Run Playground
class RestAPI {
  constructor() {
    this.calls = 0;
  }

  getUser(userId) {
    this.calls += 1;
    return { id: userId, name: 'Alice', postIds: [1, 2, 3] };
  }

  getPostDetail(postId) {
    this.calls += 1;
    return { id: postId, title: `Post ${postId}`, excerpt: '...' };
  }
}

function fetchProfileRest(userId) {
  const api = new RestAPI();
  const user = api.getUser(userId);
  const posts = user.postIds.map((pid) => api.getPostDetail(pid));
  return { user, posts, calls: api.calls };
}

class GraphQLAPI {
  constructor() {
    this.calls = 0;
  }

  query(userId) {
    this.calls += 1;
    // A single resolver walks the graph server-side and returns exactly the requested shape.
    const user = { id: userId, name: 'Alice' };
    const posts = [1, 2, 3].map((pid) => ({ id: pid, title: `Post ${pid}`, excerpt: '...' }));
    return { result: { user, posts }, calls: this.calls };
  }
}

const rest = fetchProfileRest(1);
console.log('REST round trips:', rest.calls);

const gql = new GraphQLAPI();
const gqlResult = gql.query(1);
console.log('GraphQL round trips:', gqlResult.calls);
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 5 of 99 decoded in the System Design track. One more won't hurt.

Back to track