On this page

HATEOAS and Hypermedia APIs

HATEOAS — Hypermedia As The Engine Of Application State — is the part of REST that almost every "REST API" skips. The idea is simple: the server's response does not just contain data, it contains the controls the client can use next. Links. Forms. Actions. The client starts at one known URL and discovers everything else by following what the server hands it, the same way you navigate a website without ever reading its URL scheme.

REST API Best Practices covers resource naming, verbs, and status codes, and briefly introduces HATEOAS. This page goes deep: where it came from, how to build one properly in TypeScript, the formats you can choose from, why it is genuinely better in some situations — and why the industry overwhelmingly decided not to bother.

Why It Exists

Fielding's Dissertation

In 2000, Roy Fielding published his doctoral dissertation at UC Irvine, Architectural Styles and the Design of Network-based Software Architectures. Chapter 5 defined REST — not as an API style, but as a description of the architecture that made the Web scale: millions of independently evolving servers and clients that never coordinate deployments.

REST is a set of constraints:

ConstraintWhat it meansWhat it buys
Client–serverSeparate UI concerns from data storageIndependent evolution
StatelessEach request carries everything needed to process itHorizontal scaling, simple recovery
CacheableResponses label themselves cacheable or notFewer round trips, intermediaries
Layered systemClient cannot tell if it talks to origin or a proxyCDNs, gateways, load balancers
Code on demand (optional)Server can ship executable code (JavaScript)Extensible clients
Uniform interfaceOne generic interface between all componentsDecoupling — the central feature of REST

The uniform interface is itself four sub-constraints:

  1. Identification of resources — every resource has a URI.
  2. Manipulation through representations — you change a resource by sending a representation of it (JSON, HTML), not by calling a procedure.
  3. Self-descriptive messages — each message says how to interpret itself (Content-Type, cache headers, method semantics).
  4. Hypermedia as the engine of application state — the client moves from state to state by following controls embedded in representations.

The fourth one is HATEOAS. It is not an optional extra bolted onto REST. It is the constraint that removes the need for out-of-band knowledge — the thing that lets a browser built in 2010 use a website launched yesterday.

"It Cannot Be RESTful. Period."

By 2008, "REST API" was already being used to mean "JSON over HTTP with nice URLs." Fielding wrote a blog post, REST APIs must be hypertext-driven, that is still the most-quoted line on the subject:

If the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period.

He also wrote that a REST API should be entered with no prior knowledge beyond the initial URI and a set of standardized media types, and that all subsequent transitions should be driven by the client selecting from server-provided choices. Under that definition, an API whose documentation is a list of URL patterns to hardcode is, strictly, not REST — it is RPC with good manners.

The Richardson Maturity Model

Leonard Richardson presented a maturity model at QCon in 2008, later popularized by Martin Fowler's 2010 article Richardson Maturity Model. It grades APIs by how much of the Web's architecture they actually use.

graph BT
    L0["Level 0 — The Swamp of POX<br/>One URI, one method<br/>POST /api {action: 'cancelOrder', id: 42}"]
    L1["Level 1 — Resources<br/>Many URIs, still one method<br/>POST /orders/42/cancel"]
    L2["Level 2 — HTTP Verbs<br/>Many URIs + correct methods + status codes<br/>GET /orders/42, DELETE /orders/42 → 204"]
    L3["Level 3 — Hypermedia Controls<br/>Responses carry links/actions<br/>client follows rel='cancel' instead of building the URL"]

    L0 --> L1 --> L2 --> L3

    style L0 fill:#ff6b6b,color:#fff
    style L1 fill:#ffa94d,color:#fff
    style L2 fill:#69db7c,color:#fff
    style L3 fill:#4dabf7,color:#fff
LevelClient must know in advanceTypical example
0One endpoint + an RPC vocabularySOAP, JSON-RPC, many "POST everything" internal APIs
1Every URI pattern + the action vocabularyPOST /getUser, POST /orders/42/cancel for everything
2Every URI pattern + HTTP semanticsMost public "REST" APIs today
3The entry URI + media type + link relation namesBrowsers + HTML, PayPal-style links, AtomPub, Hydra APIs

The key shift at Level 3 is what goes into the contract. At Level 2, URLs are the contract — change /orders/{id} to /v2/orders/{id} and every client breaks. At Level 3, link relation names and the media type are the contract; URLs become an implementation detail the server can change freely.

TIP

Fowler's article has an important caveat often forgotten: the model is a way to think about the elements of REST, not a definition of REST and not a scorecard where higher is always better. Level 2 is a perfectly respectable place to stop. This page is about understanding what Level 3 buys so you can make that call deliberately.

First Principles

An affordance is something in the environment that suggests an action — a door handle affords pulling. In a hypermedia response, a link or form is an affordance: its presence tells the client "you can do this, right now, and here is how."

Compare two responses for the same order.

Level 2 — data only:

{
  "id": "ord_42",
  "status": "placed",
  "total": 129.00,
  "currency": "USD",
  "customerId": "cus_7"
}

The client now has to know: placed orders can be paid and cancelled; the pay URL is POST /orders/ord_42/payments; cancelling is POST /orders/ord_42/cancel; and the customer lives at /customers/cus_7. Every one of those facts is out-of-band knowledge, duplicated in every client.

Level 3 — data plus affordances:

{
  "id": "ord_42",
  "status": "placed",
  "total": 129.00,
  "currency": "USD",
  "_links": {
    "self":     { "href": "https://api.shop.example/orders/ord_42" },
    "customer": { "href": "https://api.shop.example/customers/cus_7" },
    "payment":  { "href": "https://api.shop.example/orders/ord_42/payments" },
    "cancel":   { "href": "https://api.shop.example/orders/ord_42/cancellation" }
  }
}

The client only knows what payment and cancel mean. Where they live, and whether they are currently allowed, comes from the server.

Application State as a State Machine

"Application state" is where the client is in a workflow. Each representation is a state; each link is a transition. The server exposes the state machine by including only the transitions that are valid from the current state.

stateDiagram-v2
    [*] --> Placed: POST /orders
    Placed --> Paid: follow "payment"
    Placed --> Cancelled: follow "cancel"
    Paid --> Shipped: follow "ship" (warehouse role only)
    Paid --> Refunded: follow "refund"
    Shipped --> Delivered: follow "confirm-delivery"
    Shipped --> Returned: follow "return" (within 30 days)
    Cancelled --> [*]
    Refunded --> [*]
    Delivered --> [*]
    Returned --> [*]

    note right of Placed
        links: self, customer,
        payment, cancel, edit
    end note
    note right of Paid
        links: self, customer,
        receipt, refund
        (cancel and payment gone)
    end note
    note right of Shipped
        links: self, customer,
        receipt, tracking, return
    end note

What appears and disappears at each step:

Link relationPlacedPaidShippedDeliveredCancelled
selfYesYesYesYesYes
editYes————
paymentYes————
cancelYes————
receipt—YesYesYes—
refund—Yes———
ship—Yes (warehouse role)———
tracking——YesYes—
return——Yes (≤ 30 days)Yes (≤ 30 days)—

A client UI built against this does not ask "is the status placed and is the user the owner and is it before the payment deadline?" It asks one question: "is there a cancel link?" If yes, render the Cancel button. If no, don't.

Media Types

A media type (Content-Type) tells the client how to parse a representation and how to find the controls in it. application/json says nothing about links — a field called href is just a string. Hypermedia formats define where links live:

  • text/html — links are a and link elements; forms are form elements with method, action, and inputs.
  • application/hal+json — links live under _links, embedded resources under _embedded.
  • application/vnd.siren+json — links under links, executable actions under actions.

Picking a hypermedia media type is what makes generic tooling possible: a HAL browser can render any HAL API it has never seen before.

A link without a meaning is useless to a machine. The link relation type (rel) is the semantic: next means "the next page in a sequence", regardless of URL. RFC 8288 (Web Linking) defines the model and points to the IANA Link Relations registry for standardized names. Use registered names wherever they fit; they are understood by existing tools.

RelationMeaningTypical use
selfThe canonical URI of this representationEvery resource
collectionThe collection this item belongs toItem → list
itemA member of this collectionList → item
next / prevNext / previous in a seriesPagination
first / lastEnds of a seriesPagination
editURI to edit this resourceUpdate forms
relatedA related resourceGeneric association
alternateAnother representation (e.g. PDF, CSV)Content negotiation
describedbyDocument describing this resource (schema, profile)Discoverability
profileExtra semantics/constraints on the media typeDomain vocabularies
searchResource that can search this oneSearch entry points
latest-version / predecessor-versionVersion historyDocument APIs

For domain-specific relations (cancel, refund, ship), the spec-correct move is an extension relation: a URI such as https://api.shop.example/rels/cancel, ideally dereferenceable to human docs. HAL's curies mechanism exists to keep those readable (shop:cancel). In practice many APIs use bare names like cancel and document them — less pure, still workable if you namespace consistently.

The Browser: The One Wildly Successful HATEOAS Client

Everyone has used a HATEOAS client today. It is the browser.

sequenceDiagram
    participant U as User
    participant B as Browser (generic client)
    participant S as Shop server

    U->>B: types shop.example
    B->>S: GET /
    S-->>B: text/html with links and forms
    B-->>U: renders "Orders" link
    U->>B: clicks "Orders"
    B->>S: GET (href from the link)
    S-->>B: HTML list, each order a link
    U->>B: clicks order 42
    B->>S: GET (href)
    S-->>B: HTML with form method=POST action=.../cancellation
    U->>B: clicks "Cancel order"
    B->>S: POST (action from the form)
    S-->>B: 303 See Other → order page, no cancel form anymore

The browser knows nothing about shops, orders, or cancellation. It knows HTML (the media type) and how to follow a and submit form. The shop can rename every URL tomorrow and no browser needs an update. The missing piece in JSON APIs is the human: the browser can be generic because a person reads "Cancel order" and decides to click it. A program has no such reader — and that single fact explains most of the "why nobody uses it" section below.

Hypermedia Formats Compared

There is no single winner. Here is the same order in each major format.

HAL (Hypertext Application Language)

Media type application/hal+json. Created by Mike Kelly; specified as an IETF Internet-Draft. The most widely adopted JSON hypermedia format, and the default in Spring HATEOAS.

{
  "id": "ord_42",
  "status": "placed",
  "total": 129.00,
  "_links": {
    "self": { "href": "/orders/ord_42" },
    "curies": [
      { "name": "shop", "href": "https://docs.shop.example/rels/{rel}", "templated": true }
    ],
    "shop:customer": { "href": "/customers/cus_7" },
    "shop:payment":  { "href": "/orders/ord_42/payments" },
    "shop:cancel":   { "href": "/orders/ord_42/cancellation" },
    "shop:items":    { "href": "/orders/ord_42/items{?page}", "templated": true }
  },
  "_embedded": {
    "shop:customer": {
      "id": "cus_7",
      "name": "Ada Lovelace",
      "_links": { "self": { "href": "/customers/cus_7" } }
    }
  }
}

Strengths: tiny spec, easy to adopt incrementally, _embedded avoids extra round trips. Weakness: links only, no methods or input fields — HAL tells you where cancel is, not that it needs POST with a reason field. That stays in docs (or in HAL-FORMS, an extension that adds _templates).

JSON:API

Media type application/vnd.api+json. v1.0 was finalized in 2015, v1.1 in 2022. More than a hypermedia format — it is a complete convention for resources, relationships, sparse fieldsets, sorting, pagination, and errors.

{
  "data": {
    "type": "orders",
    "id": "ord_42",
    "attributes": { "status": "placed", "total": 129.00 },
    "relationships": {
      "customer": {
        "links": {
          "self": "/orders/ord_42/relationships/customer",
          "related": "/orders/ord_42/customer"
        },
        "data": { "type": "customers", "id": "cus_7" }
      }
    },
    "links": { "self": "/orders/ord_42" }
  },
  "included": [
    { "type": "customers", "id": "cus_7", "attributes": { "name": "Ada Lovelace" } }
  ]
}

Strengths: strong conventions, compound documents (included) solve N+1 fetching, good client libraries. Weakness: its links are mostly navigational (relationships, pagination); there is no standard way to say "cancel is available". Teams usually add custom links or meta entries for actions.

Siren

Media type application/vnd.siren+json. Created by Kevin Swiber. The format that takes actions seriously.

{
  "class": ["order"],
  "properties": { "id": "ord_42", "status": "placed", "total": 129.00 },
  "entities": [
    {
      "class": ["customer"],
      "rel": ["https://docs.shop.example/rels/customer"],
      "href": "/customers/cus_7"
    }
  ],
  "actions": [
    {
      "name": "cancel-order",
      "title": "Cancel order",
      "method": "POST",
      "href": "/orders/ord_42/cancellation",
      "type": "application/json",
      "fields": [
        { "name": "reason", "type": "text" },
        { "name": "notifyCustomer", "type": "checkbox", "value": true }
      ]
    },
    {
      "name": "pay",
      "title": "Pay for order",
      "method": "POST",
      "href": "/orders/ord_42/payments",
      "type": "application/json",
      "fields": [
        { "name": "paymentMethodId", "type": "text" },
        { "name": "amount", "type": "number", "value": 129.00 }
      ]
    }
  ],
  "links": [
    { "rel": ["self"], "href": "/orders/ord_42" },
    { "rel": ["collection"], "href": "/orders" }
  ]
}

Strengths: actions carry method, href, encoding, and fields — basically HTML forms in JSON. A generic client really can render a working UI from this. Weakness: smaller ecosystem, and payload size grows fast.

Collection+JSON

Media type application/vnd.collection+json. Created by Mike Amundsen. Designed around lists: every response is a collection with items, queries (search templates), and a write template.

{
  "collection": {
    "version": "1.0",
    "href": "/orders",
    "links": [{ "rel": "next", "href": "/orders?cursor=b2Zmc2V0OjIw" }],
    "items": [
      {
        "href": "/orders/ord_42",
        "data": [
          { "name": "status", "value": "placed" },
          { "name": "total", "value": 129.00 }
        ],
        "links": [{ "rel": "customer", "href": "/customers/cus_7" }]
      }
    ],
    "queries": [
      {
        "rel": "search", "href": "/orders/search", "prompt": "Find orders",
        "data": [{ "name": "status", "value": "" }]
      }
    ],
    "template": {
      "data": [
        { "name": "customerId", "value": "", "prompt": "Customer" },
        { "name": "sku", "value": "", "prompt": "Product SKU" }
      ]
    }
  }
}

Strengths: uniform shape, built-in search and create templates. Weakness: name/value arrays are awkward to consume as plain data; niche adoption.

JSON-LD + Hydra

JSON-LD is a W3C Recommendation for linked data in JSON; Hydra is a W3C Community Group vocabulary on top of it for describing API operations. This is the Semantic Web branch of hypermedia — every term maps to a URI in a vocabulary.

{
  "@context": "https://api.shop.example/contexts/Order.jsonld",
  "@id": "/orders/ord_42",
  "@type": "Order",
  "status": "placed",
  "total": 129.00,
  "customer": { "@id": "/customers/cus_7" },
  "operation": [
    {
      "@type": "hydra:Operation",
      "title": "Cancel order",
      "method": "POST",
      "expects": "CancellationRequest",
      "returns": "Order"
    }
  ]
}

Strengths: machine-readable semantics, schema.org interop, generic tooling exists (API Platform for PHP generates Hydra by default). Weakness: steepest learning curve; most developers find @context opaque.

You don't need a hypermedia body format at all to start. RFC 8288 defines the HTTP Link header, which works with any body — including plain JSON, images, or CSV.

HTTP/1.1 200 OK
Content-Type: application/json
Link: <https://api.shop.example/orders?cursor=b2Zmc2V0OjQw>; rel="next",
      <https://api.shop.example/orders?cursor=b2Zmc2V0OjA>; rel="first",
      <https://api.shop.example/schemas/order-list.json>; rel="describedby"

GitHub's REST API uses exactly this for pagination — clients are told to follow rel="next" rather than construct page URLs. Headers are ideal for pagination and metadata; they are poor for per-item links inside a list (one header for a 50-item page gets unwieldy).

Comparison

HALJSON:APISirenCollection+JSONJSON-LD/HydraLink header
Media typeapplication/hal+jsonapplication/vnd.api+jsonapplication/vnd.siren+jsonapplication/vnd.collection+jsonapplication/ld+jsonany
LinksYesYes (relationships, pagination)YesYesYes (@id)Yes
Actions with method + fieldsNo (HAL-FORMS adds it)NoYesCreate template + queriesYes (hydra:Operation)No
Embedded resources_embeddedincludedentitiesitemsNative graphNo
Spec sizeTinyLarge (full API convention)SmallSmallLargeTiny
EcosystemBest of the hypermedia formatsStrong, many server/client libsModestSmallModest, strong in PHPUniversal
Body stays plain dataMostlyNo (envelope)No (envelope)No (name/value)MostlyYes
Pick whenIncremental adoption, SpringYou want conventions for everythingWorkflow APIs, generic UIsList-heavy CRUDLinked data, schema.orgPagination, minimal change

TIP

A pragmatic default: plain JSON body + a links object for actions + RFC 8288 Link headers for pagination. If you want a named spec, HAL is the least disruptive. Choose Siren only if you will actually build clients that render actions generically.

Building One

The examples below use Express with TypeScript. The same structure maps directly onto Fastify or any framework — the interesting code is framework-agnostic.

Domain Model

// domain/order.ts
export type OrderStatus =
  | 'placed' | 'paid' | 'shipped' | 'delivered'
  | 'cancelled' | 'refunded' | 'returned';

export interface Order {
  id: string;
  customerId: string;
  status: OrderStatus;
  total: number;
  currency: string;
  placedAt: Date;
  shippedAt?: Date;
  trackingNumber?: string;
}

export interface Principal {
  userId: string;
  customerId?: string;
  roles: ReadonlySet<'customer' | 'support' | 'warehouse' | 'admin'>;
}

const RETURN_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;

// Business rules live here, once. Links and route guards both call these.
export const rules = {
  isOwnerOrStaff: (o: Order, p: Principal) =>
    p.customerId === o.customerId || p.roles.has('support') || p.roles.has('admin'),

  canEdit: (o: Order, p: Principal) =>
    o.status === 'placed' && rules.isOwnerOrStaff(o, p),

  canPay: (o: Order, p: Principal) =>
    o.status === 'placed' && p.customerId === o.customerId,

  canCancel: (o: Order, p: Principal) =>
    o.status === 'placed' && rules.isOwnerOrStaff(o, p),

  canRefund: (o: Order, p: Principal) =>
    o.status === 'paid' && (p.roles.has('support') || p.roles.has('admin')),

  canShip: (o: Order, p: Principal) =>
    o.status === 'paid' && p.roles.has('warehouse'),

  canReturn: (o: Order, p: Principal, now = Date.now()) =>
    (o.status === 'shipped' || o.status === 'delivered') &&
    p.customerId === o.customerId &&
    o.shippedAt !== undefined &&
    now - o.shippedAt.getTime() <= RETURN_WINDOW_MS,
};

The critical design choice: one rule function per transition, used by both the link generator and the handler that executes the transition. If they ever disagree, clients see a button that 403s — or worse, an action that succeeds without a button.

// hypermedia/links.ts
export interface Link {
  href: string;
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
  templated?: boolean;
  title?: string;
  type?: string; // media type of the target
}

export type Links = Record<string, Link>;

export class LinkBuilder {
  private readonly links: Links = {};

  constructor(private readonly baseUrl: string) {}

  /** Always add. */
  add(rel: string, path: string, extra: Omit<Link, 'href'> = {}): this {
    this.links[rel] = { href: this.abs(path), ...extra };
    return this;
  }

  /** Add only when the condition holds — this is where business rules become links. */
  addIf(cond: boolean, rel: string, path: string, extra: Omit<Link, 'href'> = {}): this {
    return cond ? this.add(rel, path, extra) : this;
  }

  build(): Links {
    return this.links;
  }

  private abs(path: string): string {
    // Templated paths contain '{' — don't let URL() percent-encode the braces.
    if (path.includes('{')) return this.baseUrl.replace(/\/$/, '') + path;
    return new URL(path, this.baseUrl).toString();
  }
}

/** Derive the public base URL from the request, honouring a trusted proxy. */
export function baseUrlFrom(req: { protocol: string; get(h: string): string | undefined }): string {
  // Express sets req.protocol from X-Forwarded-Proto only when 'trust proxy' is configured.
  return `${req.protocol}://${req.get('host')}`;
}

WARNING

Never build absolute URLs from an untrusted Host or X-Forwarded-Host header without validating it. An attacker who can poison a cache with Host: evil.example gets your API to hand out links to their server. Either pin baseUrl from configuration (PUBLIC_API_URL) or validate the host against an allowlist.

// hypermedia/order-links.ts
import { Order, Principal, rules } from '../domain/order';
import { LinkBuilder, Links } from './links';

export function orderLinks(order: Order, p: Principal, baseUrl: string): Links {
  const self = `/orders/${encodeURIComponent(order.id)}`;

  return new LinkBuilder(baseUrl)
    .add('self', self)
    .add('collection', '/orders')
    .add('customer', `/customers/${encodeURIComponent(order.customerId)}`)
    .add('items', `${self}/items{?page,size}`, { templated: true })

    // Transitions: present only when valid for THIS order and THIS caller.
    .addIf(rules.canEdit(order, p),   'edit',    self,                    { method: 'PATCH' })
    .addIf(rules.canPay(order, p),    'payment', `${self}/payments`,      { method: 'POST', title: 'Pay for order' })
    .addIf(rules.canCancel(order, p), 'cancel',  `${self}/cancellation`,  { method: 'POST', title: 'Cancel order' })
    .addIf(rules.canRefund(order, p), 'refund',  `${self}/refunds`,       { method: 'POST', title: 'Issue refund' })
    .addIf(rules.canShip(order, p),   'ship',    `${self}/shipment`,      { method: 'PUT',  title: 'Mark shipped' })
    .addIf(rules.canReturn(order, p), 'return',  `${self}/returns`,       { method: 'POST', title: 'Start a return' })

    // Read-only links that depend on state.
    .addIf(order.status !== 'placed' && order.status !== 'cancelled',
           'receipt', `${self}/receipt`, { type: 'application/pdf' })
    .addIf(order.trackingNumber !== undefined,
           'tracking', `${self}/tracking`)
    .build();
}

export function toOrderRepresentation(order: Order, p: Principal, baseUrl: string) {
  return {
    id: order.id,
    status: order.status,
    total: order.total,
    currency: order.currency,
    placedAt: order.placedAt.toISOString(),
    _links: orderLinks(order, p, baseUrl),
  };
}

Authorization and business rules are now expressed as links. A support agent sees refund; the customer looking at the same paid order does not. Nobody's client code contains the refund policy.

Handlers That Enforce the Same Rules

Links are advice, not security. The handler must re-check the rule — a client can always POST to a URL it guessed or cached.

// routes/orders.ts
import express, { Request, Response, NextFunction } from 'express';
import { rules, Order } from '../domain/order';
import { toOrderRepresentation } from '../hypermedia/order-links';
import { baseUrlFrom } from '../hypermedia/links';
import { orders } from '../db';          // repository: findById, update, list
import { principalOf } from '../auth';   // extracts Principal from the verified token

export const router = express.Router();

async function loadOrder(req: Request, res: Response): Promise<Order | undefined> {
  const order = await orders.findById(req.params.id);
  const p = principalOf(req);
  if (!order || !rules.isOwnerOrStaff(order, p)) {
    // 404, not 403: don't confirm the existence of orders the caller can't see.
    res.status(404).type('application/problem+json').json({
      type: 'https://docs.shop.example/problems/not-found',
      title: 'Order not found',
      status: 404,
    });
    return undefined;
  }
  return order;
}

router.get('/orders/:id', async (req, res, next) => {
  try {
    const order = await loadOrder(req, res);
    if (!order) return;
    res.set('Vary', 'Accept, Authorization');
    res.json(toOrderRepresentation(order, principalOf(req), baseUrlFrom(req)));
  } catch (err) { next(err); }
});

router.post('/orders/:id/cancellation', async (req, res, next) => {
  try {
    const order = await loadOrder(req, res);
    if (!order) return;
    const p = principalOf(req);

    if (!rules.canCancel(order, p)) {
      // 409 Conflict: the request is understood but the resource's state forbids it.
      return res.status(409).type('application/problem+json').json({
        type: 'https://docs.shop.example/problems/transition-not-allowed',
        title: 'Order cannot be cancelled in its current state',
        status: 409,
        detail: `Order is '${order.status}'.`,
        // Give the client a way to recover: the current representation's links.
        current: toOrderRepresentation(order, p, baseUrlFrom(req)),
      });
    }

    const updated = await orders.update(order.id, { status: 'cancelled' });
    res.json(toOrderRepresentation(updated, p, baseUrlFrom(req)));
  } catch (err) { next(err); }
});

Returning the new representation (with its new set of links) after every transition is what keeps the client in sync with the state machine without a second request.

Pagination is where hypermedia pays off immediately, even in otherwise Level 2 APIs: cursors are opaque, so clients can't build the next URL — they must follow it. See Pagination Patterns for cursor design itself.

// hypermedia/pagination.ts
import { Link } from './links';

export interface Page<T> {
  items: T[];
  nextCursor?: string;
  prevCursor?: string;
}

export function paginationLinks(
  baseUrl: string,
  path: string,
  query: URLSearchParams,
  page: Page<unknown>,
): Record<string, Link> {
  const make = (cursor?: string): string => {
    const q = new URLSearchParams(query);  // keep filters and sort
    q.delete('cursor');
    if (cursor) q.set('cursor', cursor);
    const qs = q.toString();
    return new URL(qs ? `${path}?${qs}` : path, baseUrl).toString();
  };

  const links: Record<string, Link> = {
    self: { href: make(query.get('cursor') ?? undefined) },
    first: { href: make() },
  };
  if (page.nextCursor) links.next = { href: make(page.nextCursor) };
  if (page.prevCursor) links.prev = { href: make(page.prevCursor) };
  return links;
}

/** Serialize the same links as an RFC 8288 Link header. */
export function toLinkHeader(links: Record<string, Link>): string {
  return Object.entries(links)
    .map(([rel, l]) => `<${l.href}>; rel="${rel}"`)
    .join(', ');
}
router.get('/orders', async (req, res, next) => {
  try {
    const p = principalOf(req);
    const baseUrl = baseUrlFrom(req);
    const query = new URLSearchParams(req.query as Record<string, string>);
    const page = await orders.list({
      customerId: p.roles.has('support') ? undefined : p.customerId,
      status: query.get('status') ?? undefined,
      cursor: query.get('cursor') ?? undefined,
      limit: Math.min(Number(query.get('size') ?? 20), 100),
    });

    const links = paginationLinks(baseUrl, '/orders', query, page);
    res.set('Link', toLinkHeader(links));   // for header-aware clients
    res.json({
      items: page.items.map((o) => toOrderRepresentation(o, p, baseUrl)),
      _links: links,                         // for body-only clients
    });
  } catch (err) { next(err); }
});

Templated URIs (RFC 6570)

Sometimes the client must supply a value: a search term, a page size, an ID it got elsewhere. RFC 6570 URI Templates let the server publish the shape of a URL while the client fills in variables. GitHub's API does this in its JSON — for example user objects include a following_url like https://api.github.com/users/octocat/following{/other_user}.

TemplateVariablesExpansion
/orders/{id}id = "ord 42"/orders/ord%2042
/orders{?status,size}status = "paid", size unset/orders?status=paid
/users/octocat/following{/other_user}other_user = "torvalds"/users/octocat/following/torvalds
/search{?q*}q = {term: "lamp", color: "red"}/search?term=lamp&color=red

Use a library (url-template on npm implements the full spec). If you control both sides and only need levels 1–3, a small expander is enough:

// hypermedia/uri-template.ts — supports {var}, {/var}, {?a,b}, {&a,b}. Not {+var}, {#var}, or explode (*).
// For full RFC 6570, use the 'url-template' package instead.
type Vars = Record<string, string | number | undefined>;

export function expand(template: string, vars: Vars): string {
  return template.replace(/\{([/?&]?)([^}]+)\}/g, (_, op: string, names: string) => {
    const pairs = names
      .split(',')
      .map((n) => [n.trim(), vars[n.trim()]] as const)
      .filter(([, v]) => v !== undefined && v !== '');

    if (pairs.length === 0) return '';
    const enc = (v: string | number | undefined) => encodeURIComponent(String(v));

    switch (op) {
      case '/': return pairs.map(([, v]) => '/' + enc(v)).join('');
      case '?': return '?' + pairs.map(([n, v]) => `${n}=${enc(v)}`).join('&');
      case '&': return '&' + pairs.map(([n, v]) => `${n}=${enc(v)}`).join('&');
      default:  return pairs.map(([, v]) => enc(v)).join(',');
    }
  });
}

// Self-check
console.assert(expand('/orders/{id}', { id: 'ord 42' }) === '/orders/ord%2042');
console.assert(expand('/orders{?status,size}', { status: 'paid' }) === '/orders?status=paid');
console.assert(expand('/u/octocat/following{/other}', {}) === '/u/octocat/following');

Content Negotiation

The same resource can be served as plain JSON, HAL, or HTML depending on Accept. This lets you adopt hypermedia without forcing it on every client. Background on Accept and Vary is in REST API Best Practices.

// hypermedia/negotiate.ts
import { Response } from 'express';
import { Links } from './links';

interface Rep { _links: Links; [k: string]: unknown }

export function sendOrder(res: Response, rep: Rep, renderHtml: (rep: Rep) => string) {
  res.set('Vary', 'Accept, Authorization');
  res.format({
    'application/hal+json': () => {
      // HAL: links keyed by rel, method is not part of HAL, so strip it.
      const _links = Object.fromEntries(
        Object.entries(rep._links).map(([rel, { href, templated, title, type }]) =>
          [rel, { href, templated, title, type }]),
      );
      res.type('application/hal+json').send(JSON.stringify({ ...rep, _links }));
    },

    'application/json': () => {
      // Plain JSON: keep data, move links to the Link header for clients that want them.
      const { _links, ...data } = rep;
      res.set('Link', Object.entries(_links)
        .filter(([, l]) => !l.templated)
        .map(([rel, l]) => `<${l.href}>; rel="${rel}"`).join(', '));
      res.json({ ...data, _links });
    },

    'text/html': () => res.send(renderHtml(rep)),

    default: () => res.status(406).json({ title: 'Not Acceptable', status: 406 }),
  });
}

The client below never builds a URL except the entry point. It navigates by relation name — the same way a person navigates by link text.

// client/hyper-client.ts
import { expand } from './uri-template'; // same expander as the server (or the 'url-template' package)

interface Link { href: string; method?: string; templated?: boolean }
interface Resource { _links?: Record<string, Link>; [k: string]: unknown }

export class RelNotAvailable extends Error {
  constructor(public readonly rel: string, public readonly available: string[]) {
    super(`Relation '${rel}' not available. Available: ${available.join(', ') || 'none'}`);
  }
}

export class HyperClient {
  constructor(
    private readonly entryPoint: string,
    private readonly fetchFn: typeof fetch = fetch,
    private readonly headers: Record<string, string> = {},
  ) {}

  async root(): Promise<Resource> {
    return this.request('GET', this.entryPoint);
  }

  /** Is this transition currently offered? Drives UI enable/disable. */
  can(resource: Resource, rel: string): boolean {
    return Boolean(resource._links?.[rel]);
  }

  /** Follow a relation: uses the server's href and method; expands templates. */
  async follow(
    resource: Resource,
    rel: string,
    opts: { vars?: Record<string, string | number>; body?: unknown } = {},
  ): Promise<Resource> {
    const link = resource._links?.[rel];
    if (!link) throw new RelNotAvailable(rel, Object.keys(resource._links ?? {}));

    const href = link.templated ? expand(link.href, opts.vars ?? {}) : link.href;
    return this.request(link.method ?? 'GET', href, opts.body);
  }

  /** Follow a chain of rels from the root: client.path('orders', 'next', 'next'). */
  async path(...rels: string[]): Promise<Resource> {
    let current = await this.root();
    for (const rel of rels) current = await this.follow(current, rel);
    return current;
  }

  /** Iterate every page by following rel="next" until it disappears. */
  async *pages(start: Resource): AsyncGenerator<Resource> {
    let page: Resource | undefined = start;
    while (page) {
      yield page;
      page = this.can(page, 'next') ? await this.follow(page, 'next') : undefined;
    }
  }

  private async request(method: string, url: string, body?: unknown): Promise<Resource> {
    const res = await this.fetchFn(url, {
      method,
      headers: {
        Accept: 'application/hal+json, application/json;q=0.9',
        ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
        ...this.headers,
      },
      body: body !== undefined ? JSON.stringify(body) : undefined,
    });
    if (res.status === 204) return {};
    const json = (await res.json()) as Resource;
    if (!res.ok) throw Object.assign(new Error(`HTTP ${res.status}`), { problem: json });
    return json;
  }
}

Usage — the client contains no order URLs and no cancellation rules:

const api = new HyperClient('https://api.shop.example/', fetch, {
  Authorization: `Bearer ${token}`,
});

const root = await api.root();                          // { _links: { orders, customers, search } }
const firstPage = await api.follow(root, 'orders', { vars: { status: 'placed' } });

for await (const page of api.pages(firstPage)) {
  for (const order of page.items as Resource[]) {
    if (api.can(order, 'cancel')) {
      const updated = await api.follow(order, 'cancel', { body: { reason: 'duplicate' } });
      console.log(updated.status, Object.keys(updated._links ?? {}));
      // → "cancelled" [ 'self', 'collection', 'customer', 'items' ]
    }
  }
}

In a React UI the same idea becomes trivially declarative:

function OrderActions({ order }: { order: Resource }) {
  return (
    <div>
      {api.can(order, 'payment') && <button onClick={() => pay(order)}>Pay</button>}
      {api.can(order, 'cancel')  && <button onClick={() => cancel(order)}>Cancel</button>}
      {api.can(order, 'return')  && <button onClick={() => startReturn(order)}>Return</button>}
    </div>
  );
}

Notice the honest limitation: the client still hardcodes which rels exist and what they mean (payment, cancel, return) and what body to send. HATEOAS moves URLs and availability to the server. It does not eliminate the client's need to understand the domain — no format does.

The Root Resource

Every hypermedia API needs a well-known entry point — the API equivalent of a homepage.

{
  "_links": {
    "self":      { "href": "https://api.shop.example/" },
    "orders":    { "href": "https://api.shop.example/orders{?status,cursor,size}", "templated": true },
    "order":     { "href": "https://api.shop.example/orders/{id}", "templated": true },
    "customers": { "href": "https://api.shop.example/customers" },
    "me":        { "href": "https://api.shop.example/customers/cus_7" },
    "describedby": { "href": "https://api.shop.example/openapi.json", "type": "application/openapi+json" }
  }
}

The order template is a deliberate escape hatch: clients often have an ID from somewhere else (an email, a webhook) and need to jump straight to it. Publishing the template keeps the URL pattern server-owned while allowing direct access.

htmx and Server-Rendered HTML: HATEOAS in Practice

The most practical HATEOAS today is not JSON at all. Server-rendered HTML — classic multi-page apps, Rails/Django/Laravel views, and htmx — is hypermedia by construction. The authors of htmx make exactly this argument in their book Hypermedia Systems: HTML is the hypermedia format, and the browser is the generic client that already exists.

// routes/orders-html.ts — the server returns HTML fragments with the controls embedded
import { Order, Principal, rules } from '../domain/order';

const esc = (s: string) =>
  s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]!));

export function orderCardHtml(o: Order, p: Principal): string {
  const id = encodeURIComponent(o.id);
  return `
    <article id="order-${esc(o.id)}" class="order">
      <h3>Order ${esc(o.id)}</h3>
      <p>Status: <strong>${esc(o.status)}</strong> · ${o.total.toFixed(2)} ${esc(o.currency)}</p>
      ${rules.canPay(o, p) ? `
        <a href="/orders/${id}/checkout">Pay now</a>` : ''}
      ${rules.canCancel(o, p) ? `
        <button hx-post="/orders/${id}/cancellation"
                hx-target="#order-${esc(o.id)}"
                hx-swap="outerHTML"
                hx-confirm="Cancel this order?">
          Cancel
        </button>` : ''}
      ${rules.canReturn(o, p) ? `
        <a href="/orders/${id}/returns/new">Start a return</a>` : ''}
    </article>`;
}
router.post('/orders/:id/cancellation', async (req, res) => {
  const order = await orders.findById(req.params.id);
  const p = principalOf(req);
  if (!order || !rules.isOwnerOrStaff(order, p)) return res.status(404).send('Not found');
  if (!rules.canCancel(order, p)) {
    return res.status(409).send(orderCardHtml(order, p));   // re-render current truth
  }
  const updated = await orders.update(order.id, { status: 'cancelled' });
  res.send(orderCardHtml(updated, p));  // the swapped-in card has no Cancel button
});

The returned fragment is the new state with its new affordances. There is no client-side "if status is placed, show cancel" logic anywhere. That is HATEOAS working exactly as Fielding described, which is why the htmx community talks about it far more than JSON API designers do.

TIP

If you have one web frontend and full control of the server, server-rendered HTML (with or without htmx) gives you most of HATEOAS's benefits with none of the "generic JSON client" problem — because the generic client is the browser. Separate JSON hypermedia mainly makes sense when the consumers are other programs.

Why It's Better

1. The Server Can Change URLs Without Breaking Clients

At Level 2, URL structure is a public contract forever. At Level 3, clients only depend on the entry point and rel names.

graph LR
    subgraph "Level 2 — URLs hardcoded in clients"
        C1[iOS app<br/>/orders/42/cancel] --> S1[Server]
        C2[Android app<br/>/orders/42/cancel] --> S1
        C3[Partner integration<br/>/orders/42/cancel] --> S1
        S1 -.->|"move to /fulfilment/orders/42/cancellation"| X1["3 client releases<br/>+ old route kept forever"]
    end

    subgraph "Level 3 — clients follow rel='cancel'"
        D1[iOS app] --> S2[Server]
        D2[Android app] --> S2
        D3[Partner integration] --> S2
        S2 -.->|"change href in one place"| X2["0 client releases"]
    end

    style X1 fill:#ff6b6b,color:#fff
    style X2 fill:#69db7c,color:#fff

This includes things you would not normally consider "URL changes": moving a resource to a different host or region, sharding by tenant (eu.api.example vs us.api.example), pointing a receipt link at a signed S3 URL, or routing one rel to a new microservice during a strangler migration.

2. Business Rules Live in One Place

Without links, "can this order be cancelled?" gets implemented in every client:

LocationLogicRisk
Server handlerstatus === 'placed' && isOwnerOrStaffSource of truth
Web appstatus === 'placed'Forgot the staff case
iOS appstatus === 'placed' || status === 'pending'Stale — pending was renamed two releases ago
Android appstatus !== 'shipped'Shows Cancel on cancelled orders
Partner integrationUnknownDiscovered via support tickets

With links, every client asks has(order, 'cancel'). When the business adds "orders over $5,000 can only be cancelled by support", you change rules.canCancel and every client updates instantly — including mobile apps that users have not updated in a year.

3. Discoverability

A developer (or a tool, or an LLM agent) can start at the root and explore. A HAL browser or a plain curl session shows what exists and what is possible from here. Links to describedby and profile documents point to schemas and human docs. This does not replace documentation, but it makes the running API self-consistent with it.

4. Evolvability vs Versioning

Many changes that would require a new version at Level 2 are non-breaking at Level 3:

ChangeLevel 2Level 3
Rename or restructure URLsBreaking — new version or permanent redirectsNon-breaking — update href
Add a new workflow step (e.g. fraud review between placed and paid)Clients' state logic is wrong; often breakingClients just don't see payment until review passes
Retire an actionBreaking — clients still call itStop emitting the link; clients hide the button
Move a resource to another service or hostBreaking or proxy foreverNon-breaking
Change a field's type or meaningBreakingStill breaking — hypermedia doesn't help here
Rename a link relationN/ABreaking — rels are the contract

Hypermedia does not eliminate versioning; it shrinks the set of breaking changes. See API Versioning Strategies for handling the changes it can't absorb.

5. Fewer Client Deployments

The combined effect: workflow changes, policy changes, and topology changes become server-only deploys. For mobile apps — where you can't force updates and old versions live for years — this is the most concrete payoff.

Why People Don't Use It

Being honest: full HATEOAS is rare in JSON APIs, and the reasons are mostly good ones.

1. There Is No Generic Client — Humans Read the Docs Anyway

The browser works because a human interprets "Cancel order". A program cannot decide on its own that it should cancel an order; a developer writes code that says "when the user taps X, follow cancel". That developer reads the documentation, sees the URL right there, and hardcodes it. Hypermedia's biggest benefit requires a client that doesn't know the URLs in advance, and almost no real client is like that.

2. Payload Bloat

Links are not free. A list of 100 orders, each with 8–10 absolute URLs of ~60 bytes, adds 50–60 KB of mostly redundant strings before compression. Gzip/Brotli recovers most of that (the URLs are highly repetitive), but parse time and memory on low-end mobile devices still grow, and every link is computed per request — often requiring extra data (roles, return windows) that the endpoint would not otherwise load.

3. Tooling Centers on Fixed URLs

The dominant API toolchain — OpenAPI, Postman, generated SDKs, API gateways, rate-limit rules, WAF policies — is organized around path templates. OpenAPI codegen gives you ordersApi.cancelOrder(id) which builds /orders/{id}/cancellation itself. OpenAPI 3 does have a links object for describing how responses connect to operations, but generators largely ignore it. Swimming against the toolchain costs real time.

4. Frontend Frameworks Want Data, Not Hypermedia

React, Vue, and mobile frameworks treat the server as a data source and own navigation, routing, and state on the client. A SPA router maps /orders/:id to a component; it has nowhere natural to put "the server says you can go here next." Teams that want server-driven UI tend to move to server rendering (htmx, Hotwire, Phoenix LiveView) rather than JSON hypermedia.

5. No Standard Format Won

HAL, JSON:API, Siren, Collection+JSON, Hydra, UBER, Mason, HAL-FORMS — none achieved what HTML did. Without a dominant format, there are no dominant generic clients, which means no ecosystem effect, which means less reason to adopt any format. It is a coordination failure.

6. Extra Round Trips

Strict link-following means GET / → GET orders → GET order → POST cancel: four requests where a hardcoded client needs one. Clients cache the root and templated links to avoid this, but then they are partway back to hardcoding. On high-latency mobile networks, the cost is visible.

7. "REST" Became a Synonym for JSON-over-HTTP

Most developers learned "REST" as "nouns in URLs, verbs as HTTP methods, JSON bodies." Hiring, tutorials, frameworks, and interview questions all reinforce Level 2. HATEOAS reads as academic extra credit, not as the core of the style.

8. GraphQL and tRPC Took the Evolvability Niche

The pain HATEOAS addresses — clients and servers evolving independently — got solved differently. GraphQL gives clients a typed schema, field-level deprecation, and introspection. tRPC eliminates the problem for TypeScript monorepos by sharing types end to end. Both lean on schemas and types rather than runtime links, and both fit modern frontend tooling better. See REST vs GraphQL vs gRPC vs tRPC for that trade-off.

9. Cost/Benefit for Single-Client APIs

If one team owns the server and the only client, and they deploy together, HATEOAS solves a coordination problem they don't have. Changing a URL is a single PR. The overhead — link builders, rel docs, link tests — is pure cost.

WARNING

The usual failure mode isn't "we skipped HATEOAS and regretted it." It's "we built full Siren with a generic client framework for a single SPA, and every feature took twice as long." Match the investment to the number of clients you can't redeploy.

Where It Does Pay Off

SituationWhy hypermedia helps
Public, long-lived APIs with many independent clientsYou can't coordinate deploys; URL freedom and server-side rules save versions
Workflow- and state-machine-heavy domains (orders, payments, claims, approvals, onboarding)Available actions change with state and role; links encode exactly that
Mobile apps with long-tail old versionsPolicy changes reach old apps without a release
Pagination with opaque cursorsClients can't build the URL anyway
Multi-region / sharded / migrating backendshref can point anywhere; clients don't care
LLM agents and generic automationExplicit, discoverable next actions are easier to reason about than docs

Real-world partial adoption — the pattern that actually works:

  • GitHub REST API — responses include url, html_url, and many *_url fields, several of them RFC 6570 templates (e.g. following_url, issues_url with {/number}). Pagination uses RFC 8288 Link headers with next, prev, first, last, and the docs explicitly tell clients to follow those links rather than construct page URLs.
  • PayPal REST APIs — responses carry a links array of { href, rel, method } objects. In the Orders API, creating an order returns a link with rel: "approve" that the client sends the buyer to, plus links such as self and the capture/authorize operation; integrations are expected to use those links rather than build them.

Neither is "full" HATEOAS in Fielding's sense — clients still read docs and know the domain — but both put the high-value parts (pagination, next workflow steps, URL independence) where they pay for themselves.

Decision Framework

Your situationRecommendationWhat to implement
Single web client, same team, deployed togetherSkip (or server-render HTML)Level 2; consider htmx/SSR if you want server-driven UI
Internal microservices, contract-testedSkipLevel 2 or gRPC; Link headers for pagination if REST
TypeScript monorepo, web + serverSkiptRPC or typed REST; schema sharing beats links
Mobile apps with old versions in the wildPartialAction links for state-dependent operations; pagination links
Public API, many third-party clientsPartialself links, pagination via Link header, action links on workflow resources, root resource
Workflow-heavy domain (payments, claims, approvals)Partial → FullAction links with methods; consider Siren or HAL-FORMS for fields
Many generic or semi-generic clients (admin consoles, agents, integration platforms)FullHypermedia media type, documented rel registry, root entry point, templated URIs
You want discoverability for AI agentsPartialRoot resource + action links + describedby to OpenAPI
graph TD
    A{More than one client<br/>you can't redeploy?} -->|No| SKIP[Skip — Level 2,<br/>or server-rendered HTML]
    A -->|Yes| B{Do available actions<br/>depend on state or role?}
    B -->|No| P1[Partial — self + pagination links]
    B -->|Yes| C{Will clients render<br/>actions generically?}
    C -->|No| P2[Partial — action links<br/>clients key off rel names]
    C -->|Yes| FULL[Full — Siren / HAL-FORMS / Hydra<br/>with fields and methods]

    style SKIP fill:#adb5bd,color:#fff
    style P1 fill:#69db7c,color:#fff
    style P2 fill:#4dabf7,color:#fff
    style FULL fill:#9775fa,color:#fff

TIP

"Partial" is not a cop-out — it's where nearly all successful real-world adoption sits. Action links for state-dependent operations deliver the biggest single benefit (business rules in one place) for the smallest cost.

Edge Cases and Failure Modes

The most common failure. You emit perfect links; a partner reads the docs, sees /orders/{id}/cancellation, and hardcodes it. Six months later you move the route and they break — and they are angry at you.

Mitigations:

  • Document rels, not paths. Docs say "follow the cancel link"; URL patterns appear only as examples marked "do not construct".
  • Make URLs opaque on purpose. Some teams include unguessable tokens or IDs in hrefs that only the server can produce, so hardcoding is impossible. Use sparingly — it hurts debuggability.
  • Keep old paths as redirects (308 Permanent Redirect) for a deprecation period and log who hits them. See the deprecation workflow in API Versioning.
  • Ship an official SDK that follows links internally — then most consumers get the benefit without knowing it.

Caching

Links that depend on the caller break shared caching.

  • The same GET /orders/42 returns refund for support and not for the customer. Shared caches (CDNs) must not serve one user's representation to another: send Cache-Control: private or Vary: Authorization.
  • Time-based links (return disappears after 30 days) mean a cached representation can show a stale affordance. Set max-age no longer than the shortest time-to-transition, or accept that handlers will reject with 409 and the client should refetch.
  • ETags must cover links: if the order's data is unchanged but the user's role changed, the representation changed. Include a hash of the link set (or the role) in the ETag.

See Caching for HTTP cache semantics in depth.

Links and handlers disagree: the server emits cancel, the handler returns 403; or the handler allows something the link builder never offers. Causes: duplicated rule logic, a new route without a link, or a rule change in one place only.

Mitigations:

  • One rule function per transition, used by both the link builder and the handler (as in the examples above).
  • Contract tests that walk the state machine: for every state × role, assert that following every emitted link succeeds, and that every non-emitted transition is rejected.
// test/order-links.contract.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { orderLinks } from '../hypermedia/order-links';
import { Order, Principal, OrderStatus } from '../domain/order';

const statuses: OrderStatus[] = ['placed', 'paid', 'shipped', 'delivered', 'cancelled', 'refunded', 'returned'];
const owner: Principal = { userId: 'u1', customerId: 'cus_7', roles: new Set(['customer']) };
const support: Principal = { userId: 'u2', roles: new Set(['support']) };

const base = (status: OrderStatus): Order => ({
  id: 'ord_42', customerId: 'cus_7', status, total: 10, currency: 'USD',
  placedAt: new Date(), shippedAt: status === 'shipped' ? new Date() : undefined,
});

test('cancel link appears only for placed orders', () => {
  for (const s of statuses) {
    assert.equal('cancel' in orderLinks(base(s), owner, 'https://x/'), s === 'placed', s);
  }
});

test('refund link is never shown to customers', () => {
  for (const s of statuses) {
    assert.equal('refund' in orderLinks(base(s), owner, 'https://x/'), false, s);
  }
  assert.equal('refund' in orderLinks(base('paid'), support, 'https://x/'), true);
});

// Integration layer (against a running app): for each state × principal,
// POST to every emitted action link → expect 2xx; POST to every omitted one → expect 404/409.
  • Authorization in links is a UX feature, not a security boundary. Always re-check in the handler. A missing link must never be the only thing stopping a request.
  • Don't emit links to resources the caller can't see. A link to /admin/orders/42/audit-log in a customer's response reveals the endpoint exists and invites probing. Generate admin-only links only for admins.
  • Don't leak identifiers through links. A related link to /customers/cus_7 on a shared order reveals another customer's ID. Treat hrefs as data that goes through the same field-level authorization as everything else.
  • Validate the host you build absolute URLs from (see the warning in the link builder section) to prevent cache-poisoned links to an attacker's domain.
  • Signed / expiring links (e.g. download URLs) should have short TTLs and must not be cacheable by shared caches.
  • Templated links are user input. When a client expands /orders/{id}, the server must still validate id like any path parameter.

More in API Security Patterns.

Other Sharp Edges

ProblemSymptomFix
Relative vs absolute hrefsLinks break behind a gateway that rewrites pathsEmit absolute URLs from configured public base URL
Links computed with N+1 queriesList endpoint slows down as you add action linksLoad the data rules need in bulk; or omit action links in lists and include them on the item
Rel name collisionscancel means "cancel order" on one resource, "cancel subscription" on anotherNamespace extension rels (shop:cancel-order) or scope by resource type
Clients treat missing link as errorApp crashes when payment disappears during a new review stateClient must treat absence as "not available now", never as a bug
Webhooks without linksEvent says "order 42 paid"; consumer constructs the URLInclude _links.self in webhook payloads too (see Webhooks)
Stale links after a transitionClient holds the old representation and offers Cancel againReturn the new representation (with new links) from every state-changing request

War Story

Illustrative scenario — composite of common patterns, not a specific company.

A marketplace had a web app, iOS and Android apps, and about forty partner integrations, all talking to a Level 2 order API. The rule "a buyer can cancel until the seller accepts" lived in all of them. Then the business added a fraud review step: orders over a threshold went to under_review before the seller saw them, and cancellation during review had to go through support.

The server change took a day. The client changes took a quarter. The iOS app treated any unknown status as "pending" and kept showing Cancel, which then failed with 403; old Android versions — still a meaningful share of buyers — never got the fix at all. Partners discovered the new status when their integrations threw on an unexpected enum value.

For the next workflow change, the team added _links with cancel, pay, and contact-seller to order responses, re-shipped the mobile apps to render buttons from link presence, and published "follow the cancel link" in the partner docs. When a "seller on holiday" state was added the following year, the clients needed no change at all: no contact-seller link, no button. Partners who had kept hardcoding URLs still broke when a route moved — which became the argument for shipping an official SDK that followed links internally.

The lesson they wrote down: hypermedia paid off for the state machine, not for the URLs.

Checklist

ItemDone when
Root resourceGET / returns links (and templates) to every top-level collection
self everywhereEvery resource, item in a list, and webhook payload has _links.self
PaginationOpaque cursors; next/prev/first in body and/or Link header
State-dependent actionsTransition links present only when valid for state and caller
Single rule sourceLink builder and handler call the same rule function
Handler re-checksEvery action returns 409/403/404 when the rule fails, regardless of links
New state returnedState-changing requests return the updated representation with new links
Rel docsEvery custom rel documented (meaning, method, body), ideally at a dereferenceable URI
CachingVary/private for caller-dependent links; ETags cover link sets
Absolute URLsBuilt from configured or validated base URL
Contract testsState × role matrix tests for link presence and action success

Further Reading

  • REST API Best Practices — the Level 2 foundations this page builds on
  • API Versioning Strategies — handling the breaking changes hypermedia can't absorb
  • Pagination Patterns — cursor design behind next/prev links
  • OpenAPI & Swagger — describing APIs, including the OpenAPI links object
  • API Security Patterns — authorization that links must never replace
  • REST vs GraphQL vs gRPC vs tRPC — where schema-driven evolvability wins instead
  • Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures (2000), Chapter 5
  • Roy Fielding, REST APIs must be hypertext-driven (2008)
  • Martin Fowler, Richardson Maturity Model (2010)
  • RFC 8288 — Web Linking; RFC 6570 — URI Template; IANA Link Relations registry
  • Carson Gross, Adam Stepinski, Deniz Akşimşek, Hypermedia Systems — the htmx case for HTML as the hypermedia format