ā¤ Like
šŸ”– Save
šŸ”— Share
Eric Hu
Eric Hu

API Design

@thedevspaceio

🌐 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


APIProtocolData FormatBest For
RESTHTTPJSON, XML, YAMLPublic CRUD APIs
GraphQLHTTPJSONComplex SPAs, Mobile apps
gRPCHTTP/2Protobuf (Binary)Internal microservices
WebSocketTCP (WS/WSS)Text, BinaryChats, Games, Live feeds
SOAPHTTP, SMTP, TCPXMLEnterprise B2B, Banking
WebhookHTTPJSON (usually)Callbacks, Notifications
SSEHTTPText streamLive news, Notifications
MQTTTCPBinary, JSONIoT, Sensors
AMQPTCPBinaryTask queues, Enterprise
AsyncAPIMeta-specAny (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:

MethodAction
GETRead
HEADRead headers
POSTCreate
PUTReplace/Update
PATCHPartial Update
DELETERemove
OPTIONSDiscover
TRACEDiagnostic
CONNECTTunnel

The server responds with data (usually JSON) and does not remember the client between requests (stateless).


Loading...

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).

Loading...

This is what a GraphQL query looks like:

graphql
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):

protobuf
service UserService {
  rpc GetUser (UserRequest) returns (UserResponse);
  rpc GetUsers (Empty) returns (stream UserResponse); // Server streaming
}

Loading...

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.


Loading...

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:

xml
<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>

Loading...

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.

Loading...

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:

javascript
const eventSource = new EventSource("/events");
eventSource.onmessage = (event) => {
  console.log("New event:", JSON.parse(event.data));
};

Loading...

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.

Loading...

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:

yaml
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: number

Pros:

  • 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.

@thedevspaceio
www.thedevspace.io