Back to Blogs

REST API vs GraphQL: Mana yang Lebih Cocok untuk Project Modern?

January, 2026
7 min read

🌐 REST API vs GraphQL: Mana yang Lebih Cocok untuk Project Modern?

REST API vs GraphQL

Halo para backend enthusiast! Pernah bingung mau pakai REST API atau GraphQL untuk project kalian? Keduanya punya kelebihan dan kekurangannya masing-masing. Yuk kita bedah tuntas performa, fleksibilitas, dan use case nyata dari kedua teknologi ini! πŸš€

πŸ“š Daftar Isi


πŸ€” Apa Itu REST API?

REST (Representational State Transfer) adalah arsitektur API yang udah jadi standar industri sejak tahun 2000-an. REST menggunakan HTTP methods dan endpoints untuk akses data.

Karakteristik REST:

GET    /api/users          β†’ Ambil semua users
GET    /api/users/123      β†’ Ambil user dengan ID 123
POST   /api/users          β†’ Buat user baru
PUT    /api/users/123      β†’ Update user
DELETE /api/users/123      β†’ Hapus user

Prinsip REST:

  • πŸ“ Resource-based: Setiap resource punya URL unik
  • πŸ”„ Stateless: Setiap request berdiri sendiri
  • πŸ“¦ Standard methods: GET, POST, PUT, DELETE, PATCH
  • πŸ“ JSON/XML: Format data yang umum

⚑ Apa Itu GraphQL?

GraphQL adalah query language untuk API yang dikembangkan Facebook (Meta) tahun 2015. Berbeda dari REST, GraphQL cuma punya satu endpoint dan client bisa request data sesuai kebutuhan.

Karakteristik GraphQL:

# Single endpoint: /graphql

# Query - Ambil data
query {
  user(id: "123") {
    name
    email
    posts {
      title
      content
    }
  }
}

# Mutation - Ubah data
mutation {
  createUser(name: "John", email: "john@mail.com") {
    id
    name
  }
}

Kelebihan GraphQL:

  • 🎯 Client-driven: Client tentukan data yang dibutuhkan
  • πŸ”— Single endpoint: Semua query ke satu URL
  • πŸ“Š Strong typing: Schema yang jelas dan type-safe
  • πŸš€ No over-fetching: Ambil data seperlunya aja

πŸ”„ Perbedaan Fundamental

1. Data Fetching

REST API:

// Butuh 3 request terpisah
const user = await fetch('/api/users/123')
const posts = await fetch('/api/users/123/posts')
const comments = await fetch('/api/posts/456/comments')

GraphQL:

// Cukup 1 request!
const data = await graphqlClient.query(`
  query {
    user(id: "123") {
      name
      email
      posts {
        id
        title
        comments {
          text
          author
        }
      }
    }
  }
`)

2. Over-fetching vs Under-fetching

REST - Over-fetching:

// GET /api/users/123
// Kita cuma butuh name, tapi dapet semua
{
  "id": 123,
  "name": "John Doe",
  "email": "john@mail.com",
  "phone": "+1234567890",
  "address": { ... },
  "preferences": { ... },
  "lastLogin": "2026-01-24"
}

GraphQL - Exact data:

query {
  user(id: "123") {
    name  # Cuma ambil yang dibutuhin
  }
}

3. Versioning

REST:

/api/v1/users
/api/v2/users  # Perlu bikin version baru

GraphQL:

# Cukup deprecate field, tanpa versioning
type User {
  name: String!
  email: String!
  phone: String @deprecated(reason: "Use phoneNumber instead")
  phoneNumber: String
}

βš–οΈ Perbandingan Performa

REST API Performance

Kelebihan:

  • βœ… Caching mudah: HTTP caching (GET requests)
  • βœ… CDN friendly: Static resources bisa di-cache
  • βœ… Lightweight: Request/response lebih simple

Kekurangan:

  • ❌ Multiple requests: N+1 problem
  • ❌ Over-fetching: Transfer data berlebihan
  • ❌ Under-fetching: Perlu request tambahan

Contoh N+1 Problem di REST:

// 1 request untuk users
const users = await fetch('/api/users')

// N requests untuk posts tiap user (100 users = 100 requests!)
for (const user of users) {
  const posts = await fetch(`/api/users/${user.id}/posts`)
}

GraphQL Performance

Kelebihan:

  • βœ… Single request: Ambil relational data sekaligus
  • βœ… No over-fetching: Hemat bandwidth
  • βœ… Batching: Query multiple resources sekali jalan

Kekurangan:

  • ❌ Caching kompleks: Nggak bisa pakai HTTP cache standard
  • ❌ Query complexity: Bisa bikin server overload
  • ❌ Overhead: Parsing query tambahan

Contoh Query Optimization:

# DataLoader pattern - solve N+1
query {
  users {
    name
    posts {      # Efficient batching
      title
    }
  }
}

Benchmark Sederhana:

πŸ“Š REST API:

  • Request count: 5-10 requests
  • Data size: 100% (over-fetch)
  • Cache strategy: Easy (HTTP)
  • Complexity: Low

⚑ GraphQL:

  • Request count: 1 request
  • Data size: 40-60% (exact)
  • Cache strategy: Complex (Apollo)
  • Complexity: Medium-High

🎯 Fleksibilitas dan Developer Experience

REST API DX

Pros:

// Simple dan straightforward
const express = require('express')
const app = express()

app.get('/api/users', async (req, res) => {
  const users = await db.users.findAll()
  res.json(users)
})

app.get('/api/users/:id', async (req, res) => {
  const user = await db.users.findById(req.params.id)
  res.json(user)
})

Cons:

  • Perlu maintain banyak endpoints
  • Documentation manual (Swagger/OpenAPI)
  • Frontend perlu adapt tiap ada perubahan

GraphQL DX

Pros:

// Self-documenting dengan schema
const typeDefs = `
  type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
  }

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

  type Query {
    user(id: ID!): User
    users: [User!]!
  }
`

const resolvers = {
  Query: {
    user: (_, { id }) => db.users.findById(id),
    users: () => db.users.findAll()
  },
  User: {
    posts: (user) => db.posts.findByUserId(user.id)
  }
}

Cons:

  • Learning curve lebih steep
  • Setup awal lebih kompleks
  • Perlu tools tambahan (Apollo, Relay)

Developer Tools

REST:

  • Postman
  • Insomnia
  • curl
  • Swagger UI

GraphQL:

  • GraphQL Playground
  • Apollo Studio
  • GraphiQL
  • Insomnia (support GraphQL)

πŸ’‘ Use Case Nyata

Kapan REST API Lebih Cocok? βœ…

1. Simple CRUD Applications

// Blog sederhana dengan struktur fix
GET    /api/posts
POST   /api/posts
GET    /api/posts/123
PUT    /api/posts/123
DELETE /api/posts/123

2. File Upload/Download

// REST lebih natural untuk file operations
POST /api/upload          // Multipart form-data
GET  /api/files/image.jpg // Direct file download

3. Public APIs

// Easy to consume, familiar untuk semua developer
GET https://api.github.com/users/username
GET https://api.twitter.com/tweets/123

4. Microservices Internal

// Service-to-service communication
GET http://user-service/users/123
GET http://order-service/orders/456

Kapan GraphQL Lebih Cocok? βœ…

1. Complex Data Relationships

# E-commerce dengan nested data
query {
  product(id: "123") {
    name
    price
    category {
      name
      parent {
        name
      }
    }
    reviews {
      rating
      comment
      user {
        name
        avatar
      }
    }
    relatedProducts {
      name
      price
    }
  }
}

2. Mobile Apps (Limited Bandwidth)

# Hemat data untuk mobile
query {
  user {
    name
    avatar(size: SMALL)  # Hanya ambil yang perlu
  }
}

3. Rapidly Changing Requirements

# Frontend bisa adjust query tanpa backend changes
query {
  posts {
    title
    # Besok butuh author? Tinggal tambah:
    # author { name }
  }
}

4. Aggregation dari Multiple Sources

# GraphQL sebagai API Gateway
query {
  user {
    name              # From User Service
    orders {          # From Order Service
      total
      products {      # From Product Service
        name
      }
    }
  }
}

πŸ“Š Kapan Pakai REST, Kapan Pakai GraphQL

Decision Matrix

🎯 Team Expertise:

  • REST: Beginner-friendly
  • GraphQL: Need learning

πŸ“Š Data Complexity:

  • REST: Simple/flat
  • GraphQL: Complex/nested

πŸ“± Client Variety:

  • REST: Few clients
  • GraphQL: Multiple (web, mobile, IoT)

🌐 Bandwidth Concern:

  • REST: Not critical
  • GraphQL: Critical

πŸ’Ύ Caching Need:

  • REST: High
  • GraphQL: Low-Medium

πŸ”“ Public API:

  • REST: βœ… Better
  • GraphQL: Possible

⚑ Real-time:

  • REST: WebSockets
  • GraphQL: Subscriptions βœ…

πŸš€ Development Speed:

  • REST: Fast start
  • GraphQL: Slower start, faster iteration

Real World Examples

Companies Using REST:

  • 🐦 Twitter API
  • 🎡 Spotify API
  • πŸ’³ Stripe API
  • πŸ—ΊοΈ Google Maps API

Companies Using GraphQL:

  • πŸ“˜ Facebook
  • 🎨 GitHub API v4
  • πŸ›’ Shopify
  • πŸ“Ί Netflix (internal)

Hybrid Approach? πŸ€”

Bisa kok pakai keduanya!

// REST untuk simple operations
GET  /api/health
POST /api/auth/login

// GraphQL untuk complex data fetching
POST /graphql

πŸ™Œ Penutup

Nggak ada yang "lebih baik" secara absolut antara REST dan GraphQL. Semuanya tergantung kebutuhan project kalian!

Quick Decision Guide:

Pilih REST jika:

  • βœ… Team masih belajar
  • βœ… Project simple dengan CRUD biasa
  • βœ… Butuh caching maksimal
  • βœ… Public API untuk third-party

Pilih GraphQL jika:

  • βœ… Data relationship kompleks
  • βœ… Multiple client types (web, mobile, dll)
  • βœ… Rapid feature development
  • βœ… Bandwidth efficiency penting

Tips Implementation:

  1. Mulai dari REST kalau baru belajar backend
  2. Migrate ke GraphQL kalau udah nemu pain points:
    • Too many endpoints
    • Over-fetching issues
    • Mobile performance problems
  3. Mix both kalau ada use case yang berbeda

Yang penting, pahami trade-offs masing-masing dan pilih yang sesuai dengan context project kalian! πŸ’ͺ


Remember: The best API is the one that solves your specific problems, not the one that's most hyped! 🎯