I'm mapping all my api endpoints under the base url /api/
. Now I want to expose all the available endpoints by using spring-data-rest via HATEOAS so that a client application can process these information. By default this seems to work out of the box, as a GET /api/
returns all found Spring repositories and their respective url like this:
{
"_links" : {
"news" : {
"href" : "http://localhost:8080/api/news{?page,size,sort,projection}",
"templated" : true
}
}
}
However, I would like to add some custom links to other resources. I tried this:
@RequestMapping("/api")
public class AppController {
@RequestMapping("/")
public ResponseEntity<ResourceSupport> getEndpoints () {
ResourceSupport resource = new ResourceSupport();
resource.add(linkTo(UserController.class).withRel("users"));
return new ResponseEntity<>(resource, HttpStatus.OK);
}
}
But this actually overwrites everything. So my question is how can I extend the standard output of spring-data-rest for the base resource with some custom links?
I assume you are using spring-data-rest
.
To add links to your service's index resource you have to write a ResourceProcessor<RepositoryLinksResource>
This processor will be invoked when the index resource is generated and you can use it to add links to the index resource.
Here is an example:
/**
* Adds custom controller links to the index resource
*/
@Component
public class RepositoryLinksResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
resource.add(linkTo(UserController.class).withRel("users"));
return resource;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With