C
Network/API/Lesson 05

API — REST · GraphQL · gRPC · JSON · Call Flow

45 min·theory

API — REST · GraphQL · gRPC · JSON · Call Flow

🎯 After reading this lesson

By the end of this lesson, you will be able to confidently do the following three things.

  • ✅ REST's 6 principles + Stateless · Cacheable · Uniform Interface
  • ✅ Choosing between REST, GraphQL, and gRPC
  • ✅ Writing an OpenAPI (Swagger) specification

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

REST · RESTful Design Principles

REST (Roy Fielding, 2000) — Representational State Transfer

6 Principles:
1. Client-Server — separation of concerns
2. Stateless — the server holds no state (each request is independent)
3. Cacheable — responses can be cached
4. Uniform Interface — standard methods (GET · POST · PUT · DELETE)
5. Layered — the client cannot tell whether it is talking directly to the server or through a proxy
6. Code on Demand (optional) — the server can send executable code (e.g., JavaScript)

RESTful URL Design:

ActionURLMethod
List users/usersGET
Get one user/users/42GET
Create user/usersPOST
Update user/users/42PUT/PATCH
Delete user/users/42DELETE
User's orders/users/42/ordersGET
Search/users?q=hong&age_gt=20GET

Good Response Design:

json
{
  "data": { "id": 42, "name": "Hong Gildong" },
  "meta": { "version": "v1", "timestamp": "2025-..." }
}

// Error
{
  "error": {
    "code": "USER_NOT_FOUND",
    "message": "User not found",
    "details": { "id": 42 }
  }
}

Versioning — 3 approaches:

  • URL: /v1/users (most common)
  • Header: Accept: application/vnd.api+json;version=1
  • Query string: /users?version=1

HATEOAS (the pinnacle of RESTful):

  • Include links to next possible actions in the response
  • Rarely used in practice (low practicality)

REST vs GraphQL vs gRPC

REST vs GraphQL vs gRPC — 3 paradigms:

AspectRESTGraphQLgRPC
StandardHTTPHTTP + query languageHTTP/2 + Protobuf
DataFixed responseClient-chosenFixed (Protobuf-defined)
EndpointsMultiple per resourceSingle (/graphql)RPC calls
PerformanceAverageMediumBest (binary · multiplex)
Learning curveLowMediumMedium–High
CachingLeverages HTTP cacheDifficultDifficult
Use caseGeneral web/mobile APIComplex UI · avoids over/under-fetchingInternal microservices

GraphQL — Facebook (2015):

graphql
query {
  user(id: 42) {
    name
    email
    orders(last: 5) {
      id
      total
    }
  }
}
  • Fetch only what you need in a single request
  • One backend for multiple clients (web · mobile · app)
  • Drawbacks: caching and rate limiting are complex

gRPC — Google (2015):

  • Protobuf schema definition:
proto
service UserService {
  rpc GetUser (UserId) returns (User);
  rpc StreamUsers (Filter) returns (stream User);
}
message User { int64 id = 1; string name = 2; }
  • Automatic code generation (Java · Go · Python · ...)
  • Bidirectional streaming
  • The standard for internal MSA (Google · Netflix · Uber)
  • Browsers require gRPC-Web

When to use what:

  • 🟢 REST: general external APIs · mobile · web
  • 🟢 GraphQL: complex UIs · diverse clients
  • 🟢 gRPC: internal MSA · real-time streaming

JSON + API Call Flow

JSON (JavaScript Object Notation, 2001) — the data exchange standard:

json
{
  "name": "Hong Gildong",
  "age": 28,
  "hobbies": ["coding", "reading"],
  "address": {
    "city": "Seoul",
    "zip": "06164"
  },
  "active": true,
  "registered_at": null
}

Data types:

  • string: "text" (UTF-8)
  • number: 42, 3.14, 1e10 (no distinction between integer and float)
  • boolean: true, false
  • null
  • array: [1, 2, 3]
  • object: {"key": "value"}

Pitfalls:

  • ❌ No comments (JSON5 and JSONC are separate formats)
  • ❌ No trailing commas
  • ❌ No single quotes (double quotes only)
  • ❌ No undefined
  • ✅ Integer precision: JS Number is safe only up to 2^53 — use strings for large IDs

API Call Flow (browser to DB):

code
1. JS: fetch('/api/users/42')
   └─ Browser Fetch API

2. Browser:
   - DNS lookup (codemaster40.com → IP)
   - TCP 3-way handshake + TLS handshake
   - Send request over HTTP/2 or HTTP/3

3. CDN (CloudFront, etc.):
   - Static cache hit? → respond immediately
   - Miss → forward to origin

4. Load Balancer (ALB · Nginx):
   - Which server? (round-robin · least-conn)
   - SSL termination (TLS → plaintext internally)

5. Application Server (Node · Spring):
   - Middleware (auth · logging · rate limit)
   - Router → Controller
   - Business logic

6. Cache (Redis):
   - Hit → return immediately
   - Miss → go to DB

7. Database (Postgres · MySQL):
   - Execute query (as per EXPLAIN output)
   - Result → store in cache → return response

8. Response travels in reverse
   DB → App → LB → CDN → Browser → JS

Each step is an optimization point — if one step is slow, the whole pipeline is slow.

🤖 Try asking AI like this

Once you understand the concepts in this lesson, you can give AI specific instructions. Instead of a vague 'fix this,' make vocabulary-driven requests — that is where token savings begin.

  • 'Compare the pros and cons of converting this REST API to GraphQL.'
  • 'Write an OpenAPI (Swagger) spec for this API.'

Why does this reduce tokens?

Without knowing the concepts, you have to follow up an AI answer with 'What does that mean?' That follow-up question is what eats tokens. Learn the concept once, and the conversation ends in a single exchange.

API — REST·GraphQL·gRPC·JSON - Network