Search code examples
javaspringget

Filters in the GET request


What is the best way to implement filters in a GET request?

let's say there is a method that gets a user with an id equal to 1: /user?id=1

If you need to handle a lot of similar filters /user? id=1&name=Sam&... and not necessarily all will be used. What is the best way to implement processing?

@GetMapping("/user")
public String getUser(@RequestParam("name", required=false) String name) {
    // ...
}

Solution

  • If you follow the REST conventions, you don't add the identifier as a query parameter but as a path parameter. (/users/1)

    Going back to having multiple query parameters, you have some options.

    One is as you stated it, having multiple RequestParams with the required=false option.

    @GetMapping("/user")
    public String getUser(@RequestParam(required=false) String firstName,
                          @RequestParam(required=false) String lastName,
                          @RequestParam(required=false) String nickName,
                          @RequestParam(required=false) String mail,
                          @RequestParam(required=false) String sex) {
        // ...
    }
    

    Another option is using Java8 Optional.

    @GetMapping("/user")
    public String getUser(@RequestParam Optional<String> String firstName,
                          @RequestParam Optional<String> String lastName,
                          @RequestParam Optional<String> String nickName,
                          @RequestParam Optional<String> String mail,
                          @RequestParam Optional<String> String sex) {
        // ...
    }
    

    But all in all the best way if you have multiple search options is to transform the GET request to a POST request, passing all search options in a search object. You CAN pass a request body in a GET request, but it might be ignored by some libraries/servers so it's not recommended.

    @PostMapping
    public String getUser(@RequestBody UserSearchRequest searchRequest) {
        // ...
    }