5 min read
ā¢Question 20 of 28hardWhat is HATEOAS?
Understanding Hypermedia as the Engine of Application State.
What You'll Learn
- What HATEOAS is
- Why it matters
- Implementation example
What is HATEOAS?
HATEOAS (Hypermedia as the Engine of Application State) is a REST constraint where responses include links to related actions/resources.
Why HATEOAS?
- Self-documenting API
- Clients don't need to hardcode URLs
- Server can change URLs without breaking clients
- Discoverable API
Example Without HATEOAS
data.jsonJSON
{
"id": 1,
"name": "John",
"email": "john@example.com"
}
// Client must know: GET /users/1/orders, DELETE /users/1, etc.Example With HATEOAS
data.jsonJSON
{
"id": 1,
"name": "John",
"email": "john@example.com",
"_links": {
"self": { "href": "/users/1" },
"orders": { "href": "/users/1/orders" },
"update": { "href": "/users/1", "method": "PUT" },
"delete": { "href": "/users/1", "method": "DELETE" }
}
}Implementation
code.jsJavaScript
app.get('/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
res.json({
...user.toJSON(),
_links: {
self: { href: `/users/${user.id}` },
orders: { href: `/users/${user.id}/orders` },
update: { href: `/users/${user.id}`, method: 'PUT' },
delete: { href: `/users/${user.id}`, method: 'DELETE' },
},
});
});Pagination with HATEOAS
data.jsonJSON
{
"data": [...],
"_links": {
"self": { "href": "/users?page=2" },
"first": { "href": "/users?page=1" },
"prev": { "href": "/users?page=1" },
"next": { "href": "/users?page=3" },
"last": { "href": "/users?page=10" }
}
}