I am trying to understand how to create and modify links in Spring HATEOAS.
For example, let's say I have two collections, one for api / users and one for api / event. I would like to associate the api / user / 56 user with the api / event / 21 event. For arguments, this is a lot to many - a user can attend many events, an event can have many users.
As I understand it, a cool way to do this is to use URIs as primary keys, so I can publish the following in api / user / 56 / events;
{ attends: "http://localhost:9090/api/event/21" }
Then the endpoint should be able to parse this URL and retrieve the identifier (in this case 21) and the controller (EventController.class) so that I can save this.
Question 1: Is this the correct way to relate relationships in Spring Hateoas in terms of a REST API?
Question 2: How can I resolve this URL in the controller to a useful data descriptor (for example, a link to the corresponding controller / method, primary key, etc.).
Study
RestTemplate can be used to request data from the controller inside the query matching method, for example:
RestTemplate restTemplate = new RestTemplate(); ResponseEntity<EventResource> response = restTemplate.getForEntity(attendsUrl, EventResource.class); EventResource eventResource = response.getBody();
However, I do not think that eventResource should return an Id field as part of the data - it does not really calm down, and this will be displayed in the API. One approach is to have the parameter "includePK = true", but again this does not seem to be correct - it just hides the problem. Moreover, the idea of โโa server making requests to it with its own API looks cool.
Update
There is an open question here: https://github.com/spring-projects/spring-hateoas/issues/292 . Based on some comments (from the user kevinconaway ) of this problem, I made a quick util class that offers an easy solution here: SpringHateoasUtils . The solution comes down to:
String mapping = DISCOVERER.getMapping(targetClass, targetMethod); UriTemplate template = new UriTemplate(mapping); //values is key/value map of parameters that the referenced method accepts Map<String, String> values = uriTemplate.match(uri);
SpringHateoasUtils makes this a bit nicer, but it still seems like it should be a function. I will try to get something in the Spring code for this - when it is clear what is happening with this, I will answer this question.