STACK
Ch 07 · APIs & Protocols
Chapter 07 · The contract layer

APIs & Protocols — from REST to MCP and WebTransport

Nine API protocols, the API design hygiene that separates "works" from "scales", and the versioning rules that keep clients sane for years.

7.1 · Protocol family at a glance

ProtocolTransportSchemaBest for
RESTHTTP / JSONOpenAPI 3.1Public APIs; broad clients.
GraphQLHTTP / WSSDLMany heterogeneous clients; flexible fields.
gRPCHTTP/2 + protobuf.protoInternal service-to-service, polyglot.
Connect / ConnectRPCHTTP/JSON or gRPC.protogRPC ergonomics, browser-friendly.
tRPCHTTP/JSONTS typesFull-stack TS monorepo.
JSON-RPC 2.0HTTP / WS / stdioJSON SchemaCrypto, MCP, lightweight RPC.
WebSocketWSyour choiceBi-directional real-time.
SSEHTTP—Server-to-client streams (LLM tokens, notifications).
WebTransportQUICyour choiceModern WS replacement; streams + datagrams.
WebhooksHTTPJSON SchemaServer-to-server async events.
MCPJSON-RPC over stdio/SSEJSON SchemaModel ↔ tool / resource integration (AI agents).

7.2 · REST done well

  • Resources as nouns: /orders/{id}/refunds.
  • Verbs: GET (safe), POST (create), PUT (replace), PATCH (partial), DELETE.
  • Status codes: 2xx / 3xx / 4xx / 5xx — use 409, 422 thoughtfully.
  • Pagination: cursor (?after=…) beats offset at scale.
  • Errors: stable shape ({ error: { code, message, request_id } }).
  • OpenAPI 3.1 spec is the source of truth — generate clients + docs from it.

7.3 · GraphQL

  • Schema-first; clients request only what they need.
  • Solves "N round-trips per screen" for mobile.
  • Watch out: query cost, N+1 (use DataLoader), caching is harder than REST.
  • 2026 trends: federation (Apollo, Hive), persisted queries for security + caching.

7.4 · gRPC & Connect

  • Binary protobuf over HTTP/2; bidirectional streaming; auto-generated clients in 11 languages.
  • Best for internal service mesh.
  • Connect / ConnectRPC (Buf): same .proto but also speaks HTTP/JSON — browsers, curl, gRPC all work.
  • Buf for schema management, breaking-change detection, lint.

7.5 · tRPC

Inside a TypeScript monorepo, define a router on the server; client gets typed function calls — no schema duplication, no client generation. Powerful in TS; not portable.

7.6 · JSON-RPC & MCP

  • JSON-RPC 2.0 — minimal RPC over any transport; used by Ethereum, MCP, Language Server Protocol.
  • MCP (Model Context Protocol) — JSON-RPC framing for exposing tools, resources, prompts to LLM hosts. Universal connector for AI agents (see STACK Ch 19, AI Codex Ch 11).

7.7 · WebSocket vs SSE vs WebTransport

WebSocketSSEWebTransport
DirectionFull-duplexServer → clientFull-duplex
TransportTCP via WS upgradeHTTP/1+QUIC
ReconnectYou implementBuilt-inYou implement
Streams + datagramsStreams onlyOne streamBoth
Sweet spotChat, collab, multiplayerLLM streaming, notificationsLow-latency gaming, modern WS-replacement

7.8 · Webhooks done right

  • Sign payloads (HMAC) + document verification.
  • Retry with exponential backoff; expose delivery log + replay tool.
  • Idempotent handlers — receivers will get duplicates.
  • Provide event types, versioning, sandbox.

7.9 · API design hygiene — the non-negotiables

  1. Idempotency on every write (Idempotency-Key header).
  2. Pagination — never return unbounded collections.
  3. Rate limits + clear 429 + Retry-After.
  4. Tracing headers (traceparent) propagated.
  5. Auth — OAuth 2.1 / OIDC + scopes (see Ch 08).
  6. Errors with stable codes; never raw stacks.
  7. Backwards compatibility by default; deprecation policy in writing.
  8. Bulk endpoints for high-volume clients.
  9. Field masks / sparse fieldsets.
  10. Long polls / async ops for slow work — return a job ID + status URL.

7.10 · Versioning & deprecation

  • URI versioning (/v1/...) — explicit; easy to route.
  • Header versioning (Accept: application/vnd.acme.v2+json) — clean URLs.
  • Date versioning (Stripe-style) — clients pin a date; you ship breaking changes monthly.
  • Deprecate via Sunset + Deprecation headers; provide a migration window.

7.11 · Schema-first toolchain

FormatGenerates
OpenAPI 3.1Client SDKs, docs, mock servers, contract tests.
AsyncAPISame idea for event-driven (Kafka, MQTT).
protobufgRPC / Connect clients in any language.
JSON SchemaRequest/response validation, generation.
GraphQL SDLCodegen via GraphQL Code Generator.

7.12 · Self-check

Q1 · You stream LLM tokens from server to browser. Default protocol?
WebSocket
SSE
gRPC streaming
REST long-poll