Optional Path Variable with Spring Boot Rest

I have created my own annotation with default values set overriding the existing defaults

In request parameters @RequestParam you can set the required parameters, I am implementing the Get Users and Get User by Name APIs

Legacy way of implementing

@RequestMapping(value = "/user/{name}")
 public String getUsers(@PathVariable String name) {
   return service.getUsers(name);
 }

 @RequestMapping(value = "/user")
 public String getUsers() {
   return service.getUsers();
 } 

Instead of duplicating the APIs and overloading the method we can use the Java 8 Optional Parameter

@RequestMapping(value = {"/", "/{username}"}, verb = RequestMethod.GET)
  public ResponseEntity<List<User>> getUsers(
      @PathVariable(value = "username", required = false) Optional<String> username) {
    if (username.isPresent()) {

    } else {

    }
  }

This will save a few dozen duplicate lines of code


Also published on Medium.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from

Subscribe now to keep reading and get access to the full archive.

Continue reading