Spring Rest Controller find by id/ids methods

15,795

Solution 1

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

Solution 2

Your problem is that you can't have 2 different methods on the same endpoint.

In other words, you can't have these two methods at the same time :

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

Because

@RequestMapping(value = "/{decisionIds}", method = RequestMethod.GET)

And

@RequestMapping(value = "/{decisionId}", method = RequestMethod.GET)

Are the same endpoint.

So when you have HTTP request GET on http://<host>/19, you can't determine which method you want to use.

Solution

Rename your endpoints more clearly to avoid conflicts

@RequestMapping(value = "/decision/{Id}", method = RequestMethod.GET)

And

@RequestMapping(value = "/decisions/{Id}", method = RequestMethod.GET)

I hope this will help you.

Share:
15,795
alexanoid
Author by

alexanoid

Updated on June 14, 2022

Comments

  • alexanoid
    alexanoid almost 2 years

    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?