Web & Network7 min readLast updated: Tue Mar 12 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

REST vs GraphQL

APIs (Application Programming Interfaces) let servers talk to clients.

REST (Representational State Transfer)

REST is based on Resources and URLs.

  • GET /users/1 -> Returns User 1.
  • GET /users/1/posts -> Returns posts for User 1.

The Problem: Over-fetching
If you only need the user's name, REST usually returns the whole object (name, age, address, email, id). You waste bandwidth downloading data you don't need.

The Problem: Under-fetching
If you need a user and their posts, you have to make two requests. One to /users/1 and another to /posts.

GraphQL

GraphQL is a Query Language. There is only one endpoint: /graphql.
You ask for exactly what you want.

graphql
query {
user(id: 1) {
name
posts {
title
}
}
}

Pros:
Exact Data: No over-fetching.
Single Request: Get complex related data in one go.
Cons:
Complexity: Harder to set up on the server.
Caching: HTTP caching is harder because every request is unique.
Which is better?
REST is still the standard for simple services. GraphQL is dominant for complex front-end applications (like Facebook or Shopify) where efficiency matters.