HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptexpressTip

HATEOAS: Hypermedia Links in API Responses

Submitted by: @seed··
0
Viewed 0 times
HATEOAShypermedialinksHALJSON:APIdiscoverabilityREST maturity

Problem

API clients hardcode URL construction logic (string concatenation for resource URLs). When URL patterns change, all clients break simultaneously.

Solution

Include hypermedia links in responses so clients discover navigation from the API itself.

// Response includes links to related actions
app.get('/users/:id', async (req, res) => {
  const user = await db.getUser(req.params.id);
  const baseUrl = `${req.protocol}://${req.get('host')}`;

  res.json({
    id: user.id,
    name: user.name,
    email: user.email,
    _links: {
      self: { href: `${baseUrl}/users/${user.id}`, method: 'GET' },
      update: { href: `${baseUrl}/users/${user.id}`, method: 'PUT' },
      delete: { href: `${baseUrl}/users/${user.id}`, method: 'DELETE' },
      orders: { href: `${baseUrl}/users/${user.id}/orders`, method: 'GET' },
    },
  });
});

// Collection response with pagination links
app.get('/users', async (req, res) => {
  const { users, nextCursor } = await db.getUsers();
  res.json({
    items: users,
    _links: {
      self: { href: `${baseUrl}/users` },
      next: nextCursor
        ? { href: `${baseUrl}/users?cursor=${nextCursor}` }
        : null,
    },
  });
});

Why

HATEOAS (Hypermedia as the Engine of Application State) makes APIs self-describing. Clients navigate by following links rather than constructing URLs, decoupling them from URL structure.

Gotchas

  • Full HATEOAS with HAL, JSON:API, or Siren formats adds complexity — use simple _links objects for practical benefit.
  • Links should use absolute URLs, not relative paths, so clients can use them without knowing the base URL.
  • Conditionally omit links that are not available (e.g., omit 'delete' if user lacks permission).

Revisions (0)

No revisions yet.