5
votes

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?

2
you are using spring-data-rest aren't you? - Mathias Dpunkt

2 Answers

7
votes

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;
    }
}
0
votes

under Spring Boot Version 2.4.4, you can

@Component
public class RepositoryLinksResourceProcessor extends ProfileResourceProcessor {

    /**
     * Creates a new {@link ProfileResourceProcessor} with the given {@link RepositoryRestConfiguration}.
     *
     * @param configuration must not be {@literal null}.
     */
    public RepositoryLinksResourceProcessor(RepositoryRestConfiguration configuration) {
        super(configuration);
    }

    @Override
    public RepositoryLinksResource process(RepositoryLinksResource resource) {
        return super.process(resource);
    }
}