Search code examples
springrestspring-mvcspring-restcontroller

Spring RestController url for findById and findByIds


In my Spring Boot application I have a following REST controller:

@RestController
@RequestMapping("/v1.0/decisions")
public class CriterionController {

    @Autowired
    private CriterionService criterionService;

    @RequestMapping(value = "/{decisionId}/criteria/{criterionId}", method = RequestMethod.GET)
    public CriterionResponse findById(@PathVariable @NotNull @DecimalMin("0") Long decisionId, @PathVariable @NotNull @DecimalMin("0") Long criterionId) {
        Criterion criterion = criterionService.findById(criterionId);
        return new CriterionResponse(criterion);
    }

}

Everything is working fine and I'm able to retrieve Criterion by its ID.

Right now I need to add additional logic to my CriterionController that will retrieve Criterion by a set of IDs.

Right now I'm in doubt how it can be implemented.. For example should I add a separated endpoint something like:

/{decisionId}/criteria/{criterionIds}

or for example reuse existing one for this purpose or in some other way. Please advise how to implement it according to a best practice of REST.


Solution

  • This is a tricky question, but there are 2 options I can suggest:

    /{decisionId}/criteria?id=1&id=2&id=3
    

    or

    /{decisionId}/criteria?id=1,2,3
    

    The former could be seen as more RESTful but can end up with a very long URL since you'll be specifying the query parameter each time.

    The latter aggregates the ids in a comma separated list. I personally prefer this option and would go for this.

    Although not about REST, both URLs are accepted in Section 3.2.8 of RFC 6570