Notes
All notes

Different API Styles (API Design #2)

Ask four teams to expose the same “orders” service over the network and you get four different APIs. One returns JSON documents from noun-shaped URLs. One sends XML envelopes with a formal contract in WSDL. One gives clients a query language to ask for exactly the fields they want. One streams binary messages defined in .proto files. None of them is wrong — they optimize for different consumers.

This chapter covers the four styles that dominate: REST (and its plain-JSON cousin), SOAP, GraphQL, and gRPC — what each one’s contract actually is, how resource modeling and URI design work in the REST world, the naming conventions that keep APIs guessable, and HATEOAS, the REST constraint almost nobody implements.

By the end you will be able to read an endpoint in any style and know what it assumes about its clients, and pick a style for a new service with reasons, not fashion.

What REST actually means

REST (Representational State Transfer, from Fielding’s 2000 dissertation) is a set of constraints, not a spec. The ones that do daily work:

  1. Client–server — the two sides evolve independently.
  2. Stateless — every request is self-contained (Chapter 1).
  3. Cacheable — responses declare whether they may be reused.
  4. Uniform interface — resources identified by URLs, manipulated through standard methods, represented as documents (usually JSON).
  5. Layered system — intermediaries (proxies, gateways, CDNs) can sit between client and server without either noticing.

Most “REST APIs” in production satisfy 1–4 and skip the sixth constraint (HATEOAS, below). That is fine — Richardson called these “HTTP APIs” at maturity level 2 — but you should know which constraints you are trading away, because each one you keep buys you something: statelessness buys horizontal scaling, cacheability buys free reads, uniform interface buys tooling.

Modeling resources and designing URIs

REST thinking starts with nouns. A resource is a thing your domain talks about: Package, Customer, Invoice. A collection is the plural: /packages. A member is the collection plus an id: /packages/8421. Relationships read as paths: /customers/77/orders — the orders belonging to customer 77.

The rules that keep URIs predictable:

Rule Good Bad
nouns, not verbs POST /orders POST /createOrder
plural collections /orders/42 /order/42
hierarchy for ownership /customers/77/orders /ordersByCustomer/77
query for filtering, not identity /orders?status=open /openOrders
lowercase, hyphens for words /shipping-addresses /shippingAddresses
ids opaque, never sequential guess /orders/9f3c-… /orders/10001 (enumerable)

Two judgment calls come up constantly. First, actions that are not CRUD: POST /orders/42/cancellations (model the action as creating a resource) beats POST /orders/42/cancel. Second, shallow nesting: /customers/77/orders/42 implies the order’s identity depends on the customer; prefer /orders/42 once the id exists, and use /customers/77/orders only for listing.

Four styles, one operation

Make the contrast concrete with the same operation — “fetch order 42 with its items” — in each style.

REST / simple JSON — noun URL, whole document:

GET /orders/42
→ 200 OK
{"id":"42","customer":"77","total":1999,
 "items":[{"sku":"A1","qty":2},{"sku":"B7","qty":1}]}

You get the server’s choice of fields. If your watch face only needs total, you downloaded the rest anyway (over-fetching). If you also need the customer’s name, that is a second request (under-fetching).

SOAP — XML envelope, operation in the body, contract in WSDL:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetOrder xmlns="http://example.com/orders">
      <orderId>42</orderId>
    </GetOrder>
  </soap:Body>
</soap:Envelope>

Heavyweight, but it brought real gifts: a machine-readable contract (WSDL), formal typing (XSD), and enterprise extensions (WS-Security). Banks and telecoms still run acres of it.

GraphQL — one endpoint, client writes the shape:

query {
  order(id: "42") { total  items { sku qty }  customer { name } }
}

Exactly the fields asked for, related data in one round trip. The server exposes a typed schema; the query is validated against it. The costs move server-side: expensive-query limiting, the N+1 resolver problem, and caching (no URL to key on).

gRPC — contract in Protocol Buffers, binary on HTTP/2:

service Orders {
  rpc GetOrder (GetOrderRequest) returns (Order);
}
message GetOrderRequest { string id = 1; }
message Order { string id = 1; int64 total_cents = 2; repeated Item items = 3; }

Generated clients and servers in a dozen languages, messages an order of magnitude smaller than JSON, and first-class streaming. The trade: not human-readable on the wire, and browsers cannot speak it natively (needs a proxy).

The trade-offs, quantified

The styles differ on a few axes that you can actually measure:

REST/JSON SOAP GraphQL gRPC
contract OpenAPI doc WSDL/XSD schema .proto
payload JSON text XML text JSON text binary protobuf
over/under-fetch common common solved per-method
caching HTTP-native none hard per-call
streaming bolted on no subscriptions first-class
browser-native yes yes yes no (proxy)
best fit public APIs, CRUD legacy enterprise many clients, one graph internal service-to-service

A useful mental formula for the GraphQL vs REST argument is bytes transferred per screen:

\[ B_{\text{REST}} = \sum_{r \in \text{requests}} \big( H + D_r \big), \qquad B_{\text{GQL}} = H + \sum_{f \in \text{fields}} d_f \]

where \(H\) is per-request overhead (headers, TLS record framing — hundreds of bytes) and \(D_r\) is each full document. When a screen needs three resources, REST pays \(3H\) plus three whole documents; GraphQL pays one \(H\) plus only the fields used. When a screen needs one resource in full, the formulas tie — and REST’s free HTTP caching puts it ahead.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.5cm, minimum height=0.75cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (c) at (0,0) {client};
  \node[b, fill=orange!16] (g) at (4.4,0) {GraphQL endpoint};
  \node[b, fill=green!10] (o) at (8.2,1.0) {orders svc};
  \node[b, fill=green!10] (u) at (8.2,0) {users svc};
  \node[b, fill=green!10] (i) at (8.2,-1.0) {inventory svc};
  \draw[a] (c) -- node[above, font=\rmfamily\scriptsize] {one query} (g);
  \draw[a] (g) -- (o); \draw[a] (g) -- (u); \draw[a] (g) -- (i);
\end{tikzpicture}

This is the pattern GraphQL enables: one client round trip fanned out into three internal calls — which is also why it pairs naturally with the gateway and BFF patterns of Chapter 11.

HATEOAS: the constraint nobody implements

HATEOAS (Hypermedia as the Engine of Application State) says a response should include links to the valid next actions, so clients navigate the API like a website instead of hardcoding URLs:

{
  "id": "42", "status": "pending", "total": 1999,
  "_links": {
    "self":   { "href": "/orders/42" },
    "cancel": { "href": "/orders/42/cancellations", "method": "POST" },
    "pay":    { "href": "/orders/42/payments",      "method": "POST" }
  }
}

Notice what this buys: if cancel is absent because the order already shipped, the client cannot offer a cancel button — workflow lives in the server, not in client if statements. The honest assessment: almost no public API does this, because clients are usually written once against fixed paths and the payload cost is real. But the idea survives in diluted form everywhere — pagination next links (Chapter 3) and OAuth discovery documents are HATEOAS in practice.

Choosing a style

Decide by who consumes the API:

Mixed stacks are normal: gRPC between services, REST at the edge, GraphQL for the mobile team. The style is a per-boundary decision, not a company religion.

Pitfalls

QQuestionSelf-check

Which REST constraints buy you horizontal scaling and free reads, and how? Your mobile home screen needs data from five resources — which style minimizes round trips, and what two new server-side problems does it bring? Why is /orders/10001 a worse id scheme than /orders/9f3c-…?

ASolution

Statelessness lets any replica serve any request (no session affinity), and cacheability lets intermediaries serve reads without touching your servers. GraphQL fetches five resources in one round trip, but it moves cost server-side: you must bound query depth/complexity to prevent abusive queries, and you lose URL-keyed HTTP caching. Sequential ids are enumerable — competitors can scrape your whole dataset and infer your order volume; opaque ids leak nothing and don’t advertise record counts.

Next: Building JSON / RESTful APIs (API Design #3) — design-first contracts, CRUD, filtering, pagination, and versioning in practice.