Labs ICT
Pro Login

GraphQL vs REST

GraphQL vs REST

If you've built APIs before, you're probably familiar with REST. GraphQL is often compared to REST, but they're fundamentally different approaches to building APIs. Let's understand the key differences.

How REST Works

REST (Representational State Transfer) uses HTTP methods like GET, POST, PUT, and DELETE to interact with resources. Each resource has its own endpoint.

// REST endpoints
GET    /api/users          // Get all users
GET    /api/users/1        // Get user with id 1
POST   /api/users          // Create a new user
PUT    /api/users/1        // Update user with id 1
DELETE /api/users/1        // Delete user with id 1

GET    /api/users/1/posts  // Get posts by user 1

In REST, the server decides what data to send. If you only need the user's name, you still get all their data including email, address, and other fields you might not need.

The Problems REST Solves Poorly

Over-fetching: When you request a user, you get all their fields even if you only need the name. This wastes bandwidth, especially on mobile devices.

Under-fetching: If you need a user and their posts, you have to make two requests: one to /api/users/1 and another to /api/users/1/posts. This is called the N+1 problem.

Versioning: When your API changes, you often need to create v2 endpoints. This leads to multiple versions running simultaneously.

// REST: Multiple requests needed
const user = await fetch('/api/users/1');
const posts = await fetch('/api/users/1/posts');
const followers = await fetch('/api/users/1/followers');

// GraphQL: Single request
query {
  user(id: "1") {
    name
    posts { title }
    followers { name }
  }
}

How GraphQL Solves These

No over-fetching: You specify exactly which fields you want. If you only need the name, that's all you get.

No under-fetching: You can get related data in a single query. No more multiple round trips to the server.

No versioning: Instead of versioning, you can add new fields and deprecate old ones. The schema evolves without breaking existing clients.

// GraphQL: Exactly what you need
query {
  user(id: "1") {
    name
  }
}

// GraphQL: Related data in one query
query {
  user(id: "1") {
    name
    posts {
      title
      comments {
        text
        author { name }
      }
    }
  }
}

When to Use Which

REST is still great for simple CRUD APIs, public APIs where caching is important, and when you need HTTP caching with ETags.

GraphQL shines when you have complex data requirements, need to reduce network requests, want a strongly typed API, or are building mobile apps where bandwidth matters.

Many companies use both: REST for simple endpoints and GraphQL for complex data fetching. You don't have to choose one exclusively.