API Design
TL;DR
REST: HTTP methods on resources. GraphQL: Client specifies data. gRPC: Binary protocol. Rate limiting: Prevent abuse. Versioning: Support old clients.
REST (Representational State Transfer)
GET /api/v1/users → List
GET /api/v1/users/123 → Get one
POST /api/v1/users → Create
PUT /api/v1/users/123 → Update (full)
PATCH /api/v1/users/123 → Update (partial)
DELETE /api/v1/users/123 → Delete
Best practices: Use nouns not verbs, plural resources, query params for filtering.
GraphQL
query {
user(id: "123") {
name
email
posts(limit: 5) { title }
}
}
Benefits: No over-fetching, single request for nested data.
gRPC
service UserService {
rpc GetUser (UserRequest) returns (UserResponse);
}
Benefits: Binary (7x smaller), type-safe, bi-directional streaming.
Comparison
| Aspect | REST | GraphQL | gRPC |
|---|---|---|---|
| Simplicity | ✅ Simple | ❌ Complex | ❌ Complex |
| Performance | 🟡 OK | 🟡 OK | ✅ Fast |
| Caching | ✅ HTTP | ❌ Custom | ❌ None |
| Browser | ✅ Native | ✅ Native | ❌ Proxy |
Rate Limiting
def rate_limit(user_id, limit=100, window=60):
key = f"rate_limit:{user_id}"
current = redis.incr(key)
if current == 1:
redis.expire(key, window)
if current > limit:
raise RateLimitExceeded()
Response: 429 Too Many Requests with Retry-After header.