How should I handle Hateoas from an interface?

I have this question that goes around my head for a while. Suppose we structured our project with a backend and interface at separate levels. So, from the interface, we want to get a costumer that comes in 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 external interface I want to get all transactions with clients. My question is: how do I get the URL? should it be from the answer? or should I build it internally?

if we move on to the first option, I think that perhaps it would not be elegant to iterate all the links until we get the one we need. In addition, a situation may occur when we do not have a link to the request that we want to make.

if we go with the second option, I don’t understand how to build this url if we actually have no identifiers. How can I create new transactions with clients if renoas replaces identifiers with links, and I no longer receive a reference to the object in the body?

I thought that perhaps the service should support both application/hal+json (user-oriented) and application/json (customer-oriented), but I don’t see that this is happening in general.

What do you think?

+5
source share
2 answers

Definitely the first option. Namely, since HATEOAS is the final step in the Richardson maturity model , customers should follow the provided links and not create URLs themselves:

The point of controlling hypermedia is that they tell us what we can do next, and the URI of the resource that we need to be manipulated to do this. Instead of knowing where to send an appointment request, the hypermedia control in the answer will tell us how to do it.

What benefits does this bring? I can think of at least two:

  • Simple update of REST API - server developers can change resource URIs without breaking client code, because clients simply follow the provided links; In addition, server developers can easily add new links.
  • Reliability. Following the links, the client code will never try to access broken links, errors, etc.

Q: Also, a situation may arise when we do not have a link to the request that we want to make?

The API developer must ensure that all necessary links are provided. An interface designer does not have to worry about this.

See also:

+3
source

HATEOAS (Hypermedia as an application state mechanism) is a limitation of the REST application architecture. You can look in the Spring HATEOAS documentation, for example:

https://spring.io/understanding/HATEOAS

Another link about this with Spring and AngularJS is available here:

AngularJS and Spring HATEOAS Tutorial

This one seems to be good enough and handles your use case.

Regards, Andre

+1
source

Source: https://habr.com/ru/post/1233105/


All Articles