tezvyn:

HATEOAS: Let Your API Tell You What's Next

AI-drafted, machine-checkedSource: Wikipedia: HATEOASadvanced

HATEOAS makes an API self-discoverable, like a website where you click links instead of guessing URLs. The server's response includes links for the next possible actions, decoupling the client from hardcoded endpoints.

WHY IT EXISTS HATEOAS exists to decouple clients from servers. In many APIs, clients hardcode endpoint URLs like '/users/123/orders'. If the server team renames that endpoint to '/customers/123/orders', every client application breaks. HATEOAS solves this by having the server provide the exact URLs the client needs for subsequent actions.

THE MENTAL MODEL Think of browsing a website. You start at a homepage and click links to navigate to other pages. You don't need a pre-written map of every URL on the site; the site itself guides you. HATEOAS applies this same hypermedia-driven navigation to APIs. The 'application state' is driven by the links the server provides, not by logic hardcoded in the client.

HOW IT WORKS A server implementing HATEOAS includes a special section in its JSON responses, often named '_links' or similar. This section contains a list of possible next actions as named URLs. For example, a response for a bank account might include the account balance, plus links for 'deposit', 'withdraw', and 'close-account'. The client reads the URL from the 'deposit' link to make a deposit, rather than constructing the URL itself.

WHEN TO USE IT Use HATEOAS for large-scale, public-facing, or long-lived APIs where you need to evolve the server independently of its clients. It's essential for creating truly RESTful systems that are resilient to change, as clients can adapt dynamically to new URL structures or available actions.

WHEN NOT TO USE IT For simple, internal APIs with a single, tightly-controlled client, the overhead of generating and parsing links might be unnecessary. If absolute performance is critical and every byte in the payload counts, the additional link data could be considered bloat. In these cases, a simpler JSON-over-HTTP approach may be sufficient.

ONE CANONICAL EXAMPLE A client requests data for account ID 789. The server responds with the account details and a '_links' object. The response might contain the account number, balance, and a links object with key-value pairs. For instance, the key 'self' has a value with an 'href' of '/accounts/789', and the key 'deposit' has an 'href' of '/accounts/789/deposit'. To make a deposit, the client code looks for the 'deposit' link and sends its request to that URL. If the server later changes the deposit endpoint to '/transactions/new', it simply updates the link in the response, and the client continues to function without modification.

Read the original → en.wikipedia.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.