惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
量子位
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
美团技术团队
J
Java Code Geeks
Apple Machine Learning Research
Apple Machine Learning Research
腾讯CDC
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
博客园 - 【当耐特】
L
LangChain Blog
A
About on SuperTechFans
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
Netflix TechBlog - Medium
博客园_首页
WordPress大学
WordPress大学
博客园 - Franky
Engineering at Meta
Engineering at Meta
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
GraphQL vs REST - Which One Should You Really Use?
Fazal Mansur · 2026-04-26 · via DEV Community

For years, REST APIs have been the standard.

Then GraphQL came in with promises like:

  • “Fetch exactly what you need”
  • “Reduce API calls”
  • “More flexible APIs”

But here’s the reality:

GraphQL is not a replacement for REST.
It’s a different trade-off.

Let’s break it down — with real code you can run.


🧠 What is REST?

REST is a resource-based API design.

You expose endpoints like:

GET /users/1
GET /users/1/orders

Enter fullscreen mode Exit fullscreen mode

Each endpoint returns fixed structure data.


⚙️ REST API — Fully Working Go Example

👉 Save as rest.go

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
    user := User{
        ID:    1,
        Name:  "John",
        Email: "john@example.com",
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/users/1", getUserHandler)

    log.Println("REST server running on http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Enter fullscreen mode Exit fullscreen mode

▶️ Run it

go run rest.go

Enter fullscreen mode Exit fullscreen mode

📡 Call API

curl http://localhost:8080/users/1

Enter fullscreen mode Exit fullscreen mode

📦 Response

{
  "id": 1,
  "name": "John",
  "email": "john@example.com"
}

Enter fullscreen mode Exit fullscreen mode


🧠 What is GraphQL?

GraphQL is a query-based API system.

Instead of multiple endpoints:

  • You use a single endpoint
  • Client decides what data it needs

⚙️ GraphQL API — Fully Working Go Example

👉 Save as graphql.go

Step 1: Install dependency

go mod init graphql-example
go get github.com/graphql-go/graphql

Enter fullscreen mode Exit fullscreen mode

Step 2: Full working code

package main

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/graphql-go/graphql"
)

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

var userData = User{
    ID:    1,
    Name:  "John",
    Email: "john@example.com",
}

func main() {

    // Define User type
    userType := graphql.NewObject(graphql.ObjectConfig{
        Name: "User",
        Fields: graphql.Fields{
            "id": &graphql.Field{
                Type: graphql.Int,
            },
            "name": &graphql.Field{
                Type: graphql.String,
            },
            "email": &graphql.Field{
                Type: graphql.String,
            },
        },
    })

    // Root query
    rootQuery := graphql.NewObject(graphql.ObjectConfig{
        Name: "Query",
        Fields: graphql.Fields{
            "user": &graphql.Field{
                Type: userType,
                Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                    return userData, nil
                },
            },
        },
    })

    schema, err := graphql.NewSchema(graphql.SchemaConfig{
        Query: rootQuery,
    })
    if err != nil {
        log.Fatal(err)
    }

    // GraphQL handler
    http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
        var params struct {
            Query string `json:"query"`
        }

        err := json.NewDecoder(r.Body).Decode(&params)
        if err != nil {
            http.Error(w, "invalid request body", http.StatusBadRequest)
            return
        }

        result := graphql.Do(graphql.Params{
            Schema:        schema,
            RequestString: params.Query,
        })

        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(result)
    })

    log.Println("GraphQL server running on http://localhost:8080/graphql")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Enter fullscreen mode Exit fullscreen mode

▶️ Run it

go run graphql.go

Enter fullscreen mode Exit fullscreen mode

📡 Call API

curl -X POST http://localhost:8080/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ user { name email } }"}'

Enter fullscreen mode Exit fullscreen mode

📦 Response

{
  "data": {
    "user": {
      "name": "John",
      "email": "john@example.com"
    }
  }
}

Enter fullscreen mode Exit fullscreen mode


REST vs GraphQL — Visual Understanding

REST Flow

Client
  |
  |---- GET /users/1 ----------> Server
  |---- GET /users/1/orders ---> Server
  |---- GET /orders/101/items -> Server

Multiple requests ❌

Enter fullscreen mode Exit fullscreen mode


GraphQL Flow

Client
  |
  |---- POST /graphql ---------> Server
        query {
          user {
            orders {
              items
            }
          }
        }

Single request 

Enter fullscreen mode Exit fullscreen mode


⚠️ The Real Problem GraphQL Solves

REST Problem → Over-fetching

GET /users/1

Enter fullscreen mode Exit fullscreen mode

Returns:

name, email, address, phone...

Enter fullscreen mode Exit fullscreen mode

Even if you need only name.


REST Problem → Under-fetching

You need multiple calls to build UI.


GraphQL Solution

query {
  user {
    name
  }
}

Enter fullscreen mode Exit fullscreen mode

👉 Exact data only.


⚖️ REST vs GraphQL — Honest Comparison

🧩 REST

✅ Simple
✅ Easy caching
✅ Easy debugging
❌ Multiple calls
❌ Over-fetching


🧩 GraphQL

✅ Flexible
✅ Single request
❌ Complex
❌ Hard caching

Note: REST uses native HTTP caching (like CDNs and browser headers), while GraphQL requires complex, custom caching strategies because queries are typically sent via POST.

❌ Query abuse risk


⚠️ Common Mistakes

❌ “GraphQL is always better”

No.

❌ Using GraphQL for simple CRUD

Overkill.

❌ Ignoring query complexity

Bad query:

users → posts → comments → replies → ...

Enter fullscreen mode Exit fullscreen mode

💥 Performance issue


🧠 When to Use What

✅ Use REST when:

  • Simple APIs
  • CRUD operations
  • Strong caching needed
  • Easy debugging required

✅ Use GraphQL when:

  • Complex frontend
  • Aggregated data
  • Multiple services
  • Frequent UI changes

🔗 Real-World Architecture

Many companies use the GraphQL Gateway (or BFF) pattern:

Frontend → GraphQL Gateway → REST microservices

Enter fullscreen mode Exit fullscreen mode

👉 GraphQL acts as an aggregation layer, allowing you to combine multiple REST responses into one, without refactoring the legacy backend.


🏁 Final Thoughts

GraphQL vs REST is not a battle.

It’s a design decision.


🎯 Key Takeaways:

  • REST = simple and predictable
  • GraphQL = flexible but complex
  • Both solve real problems
  • Choose based on use-case

🚀 Final Tip

If your API:

👉 Is simple → use REST
👉 Needs flexibility → use GraphQL