javaspringspring-data

Is there a way to filter or sort data in a RESTful API?


From my understanding (although I am just learning this so I am likely wrong), we use URIs in RESTful APIs to identify resources.

In particular, I've read this comment many times across the web:

@RequestParam is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable is more suitable for RESTful web services where URL contains values.

When reading this, it seems like we need to use @PathVariable to properly build a RESTful API instead of using @RequestParam (which is not RESTFUL given the way it identifies resources through query parameters instead of URIs). Is this correct? If so, how can I build a RESTful API that is also capable of sorting or filtering like you would be able to do with @RequestParam?

An example is here:

@GetMapping("/{id}")
Resource<Car> get(@PathVariable Long id) {
   Car car = carService.findById(id);
   return assembler.toResource(car);
}

vs

@GetMapping("/{id}")
Resource<Car> get(@RequestParam(required = true) Long id) {
    Car car = carService.findById(id);
    return assembler.toResource(car);
}

Solution

  • You should examine the Pageable type in Spring. Generally, what you've shown here is called something like an item resource: It's one specific Car, specified by ID at /cars/{id}. There's nothing to sort or filter. Those are applied to the collection resource /cars, perhaps something like /cars?sort=year&page=0&size=10. Spring has integrated support for automatically extracting query parameters indicating sorting and paging and passing those instructions to Spring Data repositories.