Search code examples
springrestspring-mvcspring-restcontroller

Spring Rest Controller find by id/ids methods


I have the following method in my Spring RestController:

@RequestMapping(value = "/{decisionId}", method = RequestMethod.GET)
    public DecisionResponse findById(@PathVariable @NotNull @DecimalMin("0") Long decisionId) {
....
}

Right now I need to add the possibility to find a set of DecisionResponse by {decisionIds}.. something like this:

@RequestMapping(value = "/{decisionIds}", method = RequestMethod.GET)
    public List<DecisionResponse> findByIds(@PathVariable @NotNull @DecimalMin("0") Set<Long> decisionIds) {
....
}

The following two methods don't work together.

What is a correct way of implementing this functionality? Should I leave only one method(second) that waits for {decisionIds} and returns a collection even when I need only 1 Decision object? Is there another proper way to implement this?


Solution

  • You can create a single endpoint for both sending a single long value as well as for the array of long values:

    @RequestMapping(value = "/{decisionIds}", method = RequestMethod.GET)
        public List<DecisionResponse> findByIds(@PathVariable @NotNull @DecimalMin("0") Set<Long> decisionIds) {
              System.out.println(decisionIds);
    }
    

    And call this endpoint by sending path variable like this:

    http://localhost:8080/11,12,113,14