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.

Default image
Vignesh A Sathiyanantham
AWS Certified developer with 8 years of extensive experience working for Cloud and Datacenter solutions and leading a small team in a lean startup based on Bangalore, India

Leave a Reply

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