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

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?
- β‘ Apa Itu GraphQL?
- π Perbedaan Fundamental
- βοΈ Perbandingan Performa
- π― Fleksibilitas dan Developer Experience
- π‘ Use Case Nyata
- π Kapan Pakai REST, Kapan Pakai GraphQL
- π Penutup
π€ 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:
- Mulai dari REST kalau baru belajar backend
- Migrate ke GraphQL kalau udah nemu pain points:
- Too many endpoints
- Over-fetching issues
- Mobile performance problems
- 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! π―