
API Design
š The Ultimate API Architecture Cheatsheet
The API landscape is huge, and it is not just REST. Here are the 10 architectures and when to use each:
ā REST API: The classic. Simple, stateless, resource-based. Good for most CRUD apps. ā GraphQL: Query exactly what you need. Perfect for complex frontends and mobile. ā gRPC: High-performance, binary, streaming. Ideal for microservices. ā WebSocket: Full-duplex, real-time. Chat, gaming, live updates. ā SOAP: The enterprise veteran. Strict, secure, XML-heavy. Banking, legacy. ā Webhook: Event-driven, push notifications. Goodbye polling. ā SSE: One-way real-time. Live dashboards, news feeds. ā MQTT: Lightweight, publish/subscribe. IoT, mobile, low-bandwidth. ā AMQP: Reliable, queuing, routing. Message brokers, enterprise. ā AsyncAPI: Event-driven docs. The OpenAPI of async APIs.
Save this. Share it. Never pick the wrong protocol again. š
#api #rest #graphql #grpc #websocket #webdev #backend #systemdesign
| API | Protocol | Data Format | Best For |
|---|---|---|---|
| REST | HTTP | JSON, XML, YAML | Public CRUD APIs |
| GraphQL | HTTP | JSON | Complex SPAs, Mobile apps |
| gRPC | HTTP/2 | Protobuf (Binary) | Internal microservices |
| WebSocket | TCP (WS/WSS) | Text, Binary | Chats, Games, Live feeds |
| SOAP | HTTP, SMTP, TCP | XML | Enterprise B2B, Banking |
| Webhook | HTTP | JSON (usually) | Callbacks, Notifications |
| SSE | HTTP | Text stream | Live news, Notifications |
| MQTT | TCP | Binary, JSON | IoT, Sensors |
| AMQP | TCP | Binary | Task queues, Enterprise |
| AsyncAPI | Meta-spec | Any (JSON, Avro) | Documenting event systems |
1. REST API
REST treats everything as a resource (like /users, /orders). You interact with these resources using standard HTTP verbs:
| Method | Action |
|---|---|
GET | Read |
HEAD | Read headers |
POST | Create |
PUT | Replace/Update |
PATCH | Partial Update |
DELETE | Remove |
OPTIONS | Discover |
TRACE | Diagnostic |
CONNECT | Tunnel |
The server responds with data (usually JSON) and does not remember the client between requests (stateless).
Pros:
- Simple and well-understood
- Built-in HTTP caching
- Stateless, easy to scale horizontally
Cons:
- Over-fetching: gets more data than needed
- Under-fetching: needs multiple roundtrips for related data
2. GraphQL
The client sends a query that describes exactly what data it wants. The server returns only that data in one response. All requests go to a single endpoint (usually /graphql).
This is what a GraphQL query looks like:
query {
user(id: 1) {
name
email
posts {
title
}
}
}Pros:
- No over/under fetching
- Strong type system (SDL)
- Single roundtrip
Cons:
- Hard to cache
- N+1 problem on the server
- Complex rate limiting
3. gRPC (Google RPC)
You define a service and its messages using Protocol Buffers (a binary format).
The server and client then automatically generate code in various languages.
Communication happens over HTTP/2.
Example Service Definition (.proto file):
service UserService {
rpc GetUser (UserRequest) returns (UserResponse);
rpc GetUsers (Empty) returns (stream UserResponse); // Server streaming
}Pros:
- Blazing fast (binary protocol)
- Supports streaming (bi-directional)
- Strong contracts and code generation
Cons:
- Not human-readable
- Browser support is limited
- Harder to debug
4. WebSocket
The client initiates an HTTP upgrade request to switch to the WebSocket protocol.
Once connected, both sides can send messages at any time over a persistent, full-duplex channel.
Pros:
- Real-time, low latency
- Full-duplex (both can send)
- Efficient (no HTTP headers per message)
Cons:
- Stateful, harder to scale
- No built-in reconnection logic
- No native routing
5. SOAP (Simple Object Access Protocol)
A strict XML-based protocol.
You define a WSDL (Web Services Description Language) file that describes the service's operations, inputs, and outputs.
Messages are wrapped in XML envelopes with defined headers and bodies.
SOAP Request Example:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<Security>...</Security> <!-- WS-Security -->
</soap:Header>
<soap:Body>
<GetBalance>
<AccountID>12345</AccountID>
</GetBalance>
</soap:Body>
</soap:Envelope>Pros:
- ACID transactions
- End-to-end security (WS-Security)
- Strict contracts (great for enterprise)
Cons:
- Heavy XML payloads
- Slow to parse
- Inflexible and complex
6. Webhook
Instead of the client polling the server, the server calls the client when an event happens.
The client provides a URL, and the server sends an HTTP request (usually POST with JSON) to it.
Pros:
- Eliminates polling
- Simple HTTP-based
- Decouples systems
Cons:
- No built-in retry
- Security concerns
- Unreliable if receiver is down
7. SSE (Server-Sent Events)
The client opens a persistent HTTP connection to the server. The server sends text data (events) over this connection whenever new information is available. The browser's EventSource API handles it natively.
Client Code:
const eventSource = new EventSource("/events");
eventSource.onmessage = (event) => {
console.log("New event:", JSON.parse(event.data));
};Pros:
- Native browser support
- Auto-reconnection built-in
- Lightweight
Cons:
- Only server, client
- Browser connection limits
- No binary data support
8. MQTT (Message Queuing Telemetry Transport)
A Pub/Sub (Publish/Subscribe) system with a central Broker. Devices publish messages to topics (like /house/kitchen/temperature), and other devices that have subscribed to that topic receive the message.
QoS (Quality of Service) Levels
- 0, At most once (fire and forget)
- 1, At least once (guaranteed delivery)
- 2, Exactly once (two-step handshake)
Pros:
- Extremely lightweight
- QoS for reliability
- Good for low-bandwidth networks
Cons:
- Broker can be a single point of failure
- Weak query capabilities
9. AMQP (Advanced Message Queuing Protocol)
A feature-rich messaging protocol built around Exchanges, Queues, and Bindings. The producer sends messages to an Exchange, which routes them to Queues based on Bindings. Consumers pull messages from these queues.
Exchange Types
- Direct: Routes to queue with matching routing key
- Topic: Routes by pattern (wildcards)
- Fanout: Broadcasts to all queues
- Headers: Routes by message headers
Pros:
- Guaranteed delivery (with ACKs)
- Complex routing capabilities
- Transaction support
Cons:
- Heavy and complex
- Requires significant configuration
10. AsyncAPI
Not a protocol. It's a specification to document event-driven systems (like Kafka, MQTT, WebSockets). It's the "OpenAPI" for asynchronous APIs.
AsyncAPI Document Example:
asyncapi: "2.6.0"
info:
title: Order Service
version: "1.0.0"
channels:
order/created:
subscribe:
message:
payload:
type: object
properties:
orderId:
type: string
total:
type: numberPros:
- Documents chaotic event systems
- Auto-generates client/servers
- Works with Kafka, MQTT, AMQP, etc.
Cons:
- Relatively new
- Tooling is still maturing
Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.