Reputation: 6189
I have this question that has been going around through my head for a while. Lets suppose we have structured our project with backend and frontend on separate layers. So, from the frontend, we want to get a costumer, which comes on hal+json
format:
GET /customers/1 HTTP/1.1
Accept: application/hal+json
{
"name": "Alice",
"links": [ {
"rel": "self",
"href": "http://localhost:8080/customer/1"
} {
"rel": "transactions",
"href": "http://localhost:8080/customer/1/transactions"
}]
}
Then, from the frontend i want to get all customer transactions. My question is: how should i get the url? should it be from the response? or should i build it internally?
if we go with first option, i think that maybe that wouldn't be elegant to iterate all links until we get that one we want. Also, there could happen the situation where we don't have the link of the request we want to do.
if we go with second option, i don't understand how to build that url if we don't actually have the ids. How could i create new customer transactions if hateoas replaces ids with links and i haven't got the object reference in the body anymore?
I thought that maybe service should support both application/hal+json
(oriented to users) and application/json
(oriented to clients) but i don't see that this is how is making it done generally.
What do you think?
Upvotes: 8
Views: 3696
Reputation: 15251
Definitely the first option. Namely, since HATEOAS is a final stage of Richardson Maturity Model, clients are expected to follow the provided links, not to build the URLs by themselves:
The point of hypermedia controls is that they tell us what we can do next, and the URI of the resource we need to manipulate to do it. Rather than us having to know where to post our appointment request, the hypermedia controls in the response tell us how to do it.
What benefits does this bring? I can think of at least two:
Q: Also, there could happen the situation where we don't have the link of the request we want to do?
It is up to API designer to ensure that all required links are provided. Front-end developer shouldn't worry about that.
See also:
Upvotes: 4
Reputation: 760
HATEOAS (Hypermedia as the Engine of Application State) is a constraint of the REST application architecture. You can have a look on Spring HATEOAS documentation for instance :
https://spring.io/understanding/HATEOAS
Another link about it using Spring and AngularJS is available here:
AngularJS and Spring HATEOAS tutorial
This one seems to be good enough and handles your use case.
Regards, André
Upvotes: 2