API Design: REST, gRPC, GraphQL
An API is the contract between a service and its clients. Once other teams or apps depend on it, it is expensive to change, so it deserves as much design care as the database schema. Three styles dominate.
| REST | gRPC | GraphQL | |
|---|---|---|---|
| Transport | HTTP/1.1 or 2, usually JSON | HTTP/2, Protocol Buffers (binary) | HTTP, usually one POST /graphql endpoint, JSON |
| Model | Resources + HTTP verbs | Remote procedure calls defined in .proto files |
A typed graph; clients ask for exactly the fields they need |
| Strengths | Simple, cacheable, universal tooling | Fast, compact, streaming, generated clients | No over-/under-fetching, one round trip for nested data |
| Weaknesses | Over-fetching, many round trips for nested data | Not browser-native, harder to debug by hand | Caching is harder, expensive queries need limits |
| Typical use | Public APIs, web/mobile backends | Service-to-service inside a company | Product frontends with many screens |
REST: resources and verbs
REST models nouns (/users/42/orders) and uses HTTP methods for actions. Status codes carry the outcome.
| Method | Meaning | Idempotent? | Example | Success |
|---|---|---|---|---|
GET |
Read | Yes | GET /orders/7 |
200 OK |
POST |
Create / non-idempotent action | No | POST /orders |
201 Created + Location |
PUT |
Replace | Yes | PUT /orders/7 |
200 / 204 |
PATCH |
Partial update | Not necessarily | PATCH /orders/7 |
200 |
DELETE |
Remove | Yes | DELETE /orders/7 |
204 No Content |
A tiny in-memory REST handler shows the conventions:
import json
orders, next_id = {}, 1
def handle(method, path, body=None):
global next_id
parts = path.strip("/").split("/")
if parts[0] != "orders":
return 404, {"error": "not found"}
if len(parts) == 1:
if method == "GET":
return 200, {"items": list(orders.values())}
if method == "POST":
if not body or "item" not in body:
return 422, {"error": "field 'item' is required"}
order = {"id": next_id, "item": body["item"], "status": "new"}
orders[next_id], next_id = order, next_id + 1
return 201, order
return 405, {"error": "method not allowed"}
order_id = int(parts[1])
if order_id not in orders:
return 404, {"error": f"order {order_id} not found"}
if method == "GET":
return 200, orders[order_id]
if method == "PATCH":
orders[order_id].update(body)
return 200, orders[order_id]
if method == "DELETE":
del orders[order_id]
return 204, None
return 405, {"error": "method not allowed"}
requests = [("POST", "/orders", {"item": "lamp"}), ("POST", "/orders", {}),
("GET", "/orders/1", None), ("PATCH", "/orders/1", {"status": "paid"}),
("DELETE", "/orders/1", None), ("GET", "/orders/1", None)]
for method, path, body in requests:
status, response = handle(method, path, body)
print(f"{method:<6} {path:<10} -> {status} {json.dumps(response)}")POST /orders -> 201 {"id": 1, "item": "lamp", "status": "new"}
POST /orders -> 422 {"error": "field 'item' is required"}
GET /orders/1 -> 200 {"id": 1, "item": "lamp", "status": "new"}
PATCH /orders/1 -> 200 {"id": 1, "item": "lamp", "status": "paid"}
DELETE /orders/1 -> 204 null
GET /orders/1 -> 404 {"error": "order 1 not found"}
Pagination: offset vs cursor
Lists must be paginated. ?offset=40&limit=20 is easy, but the database still walks past 40 rows, and if new rows arrive while a user pages, items shift and get skipped or repeated. A cursor ("give me 20 items after id 1234") is stable and uses an index directly.
posts = list(range(100, 90, -1)) # newest first: ids 100..91
def offset_page(data, offset, limit):
return data[offset:offset + limit]
def cursor_page(data, after, limit):
rest = [p for p in data if after is None or p < after]
page = rest[:limit]
return page, (page[-1] if page else None)
page1 = offset_page(posts, 0, 3)
posts.insert(0, 101) # a new post arrives between requests
page2 = offset_page(posts, 3, 3)
print("offset:", page1, page2, "<- 98 shown twice")
posts = list(range(100, 90, -1))
page1, cursor = cursor_page(posts, None, 3)
posts.insert(0, 101)
page2, cursor = cursor_page(posts, cursor, 3)
print("cursor:", page1, page2, "next cursor:", cursor)offset: [100, 99, 98] [98, 97, 96] <- 98 shown twice
cursor: [100, 99, 98] [97, 96, 95] next cursor: 95
gRPC and binary encoding
gRPC services are defined in a .proto file, from which client and server code is generated:
service Orders {
rpc GetOrder (GetOrderRequest) returns (Order);
rpc WatchOrders (WatchRequest) returns (stream OrderEvent); // server streaming
}
message Order { int64 id = 1; string item = 2; int32 quantity = 3; }Protocol Buffers send field numbers instead of names and encode integers as variable-length "varints", so messages are much smaller than JSON. Here is a hand-rolled encoder for the Order message above:
import json
def varint(n):
out = bytearray()
while True:
byte = n & 0x7F
n >>= 7
out.append(byte | (0x80 if n else 0))
if not n:
return bytes(out)
def encode_order(order_id, item, quantity):
data = item.encode()
return (bytes([1 << 3 | 0]) + varint(order_id) # field 1, varint
+ bytes([2 << 3 | 2]) + varint(len(data)) + data # field 2, length-delimited
+ bytes([3 << 3 | 0]) + varint(quantity)) # field 3, varint
binary = encode_order(150, "desk lamp", 2)
text = json.dumps({"id": 150, "item": "desk lamp", "quantity": 2}).encode()
print("protobuf:", binary.hex(" "))
print(f"protobuf {len(binary)} bytes vs JSON {len(text)} bytes")protobuf: 08 96 01 12 09 64 65 73 6b 20 6c 61 6d 70 18 02
protobuf 16 bytes vs JSON 47 bytes
GraphQL: ask for exactly what you need
A GraphQL client sends a query describing the shape it wants; the server's resolvers fill it in. A mobile screen that only needs a name and the titles of three orders gets exactly that, in one request:
users = {1: {"id": 1, "name": "Ada", "email": "ada@example.com", "bio": "x" * 500}}
orders = [{"user": 1, "title": t, "total": n} for t, n in [("lamp", 40), ("desk", 220), ("pen", 3), ("mug", 9)]]
def resolve(selection, obj):
result = {}
for field, sub in selection.items():
if field == "orders":
mine = [o for o in orders if o["user"] == obj["id"]][: sub.get("_first", 10)]
result["orders"] = [resolve({k: v for k, v in sub.items() if k != "_first"}, o) for o in mine]
else:
result[field] = obj[field]
return result
# query { user(id: 1) { name orders(first: 3) { title } } }
query = {"name": None, "orders": {"_first": 3, "title": None}}
print(resolve(query, users[1])){'name': 'Ada', 'orders': [{'title': 'lamp'}, {'title': 'desk'}, {'title': 'pen'}]}
The REST equivalent would be GET /users/1 (returning the whole profile, including a long bio) plus GET /users/1/orders. GraphQL needs safeguards in exchange: depth and cost limits, and batching (the "DataLoader" pattern) to avoid N+1 database queries in resolvers.
Design guidelines
- Version public APIs (
/v1/, or a header) and evolve them additively: add optional fields, never change the meaning of existing ones. - Return consistent errors: a status code plus a machine-readable body (
{"error": {"code": "out_of_stock", "message": "..."}}). - Make writes idempotent where possible (
PUT, orIdempotency-Keyheaders onPOST; see Idempotency and Retries). - Paginate every list, rate-limit every endpoint, and document both.
Test yourself
Which HTTP method is NOT idempotent by definition?
- GET
- PUT
- DELETE
- POST
Why is cursor pagination more robust than offset pagination?
- It is shorter to type
- Inserting new items doesn't shift the pages, and it uses an index to seek directly
- It returns more items
- It works without a database
Why are Protocol Buffers messages smaller than equivalent JSON?
- They are compressed with gzip
- They send field numbers instead of names and use compact varint integers
- They drop string fields
- They only support numbers