Using a nested object in a GET request in Spring Boot REST

November 22nd 2021

I'm not sure why this answer was so hard to find, so I'm posting it clearly here. Using Spring Boot REST for a GET request, I just wanted to be able to encapsulate many RequestParams into a single object. So instead of something like this...

@RequestMapping(value = "/users", method = RequestMethod.GET)
List<User> getUsers(@RequestParam String firstName, @RequestParam String lastName);

...I wanted to encapsulate all of those filter params into a class like this:

public class Filters {
  private String firstName;

  private String lastName;

  ... more properties and then getters and setters

What tripped me up was that there were a bunch of posts that were saying that you should use dot notation, so like /foo?filters.firstName=Ben, but for me at least, this did not work.

Instead, the simplest solution was to just remove the @RequestParam altogether:

@RequestMapping(value = "/users", method = RequestMethod.GET)
List<User> getUsers(Filters filters);

And that was it. Spring magic for the win!

I'm an "old" programmer who has been blogging for almost 20 years now. In 2017, I started Highline Solutions, a consulting company that helps with software architecture and full-stack development. I have two degrees from Carnegie Mellon University, one practical (Information and Decision Systems) and one not so much (Philosophy - thesis here). Pittsburgh, PA is my home where I live with my wife and 3 energetic boys.
I recently released a web app called TechRez, a "better resume for tech". The idea is that instead of sending out the same-old static PDF resume that's jam packed with buzz words and spans multiple pages, you can create a TechRez, which is modern, visual, and interactive. Try it out for free!
Got a Comment?

Comments (0)

 None so far!