Optional Path Variable with Spring Boot Rest

Vignesh A Sathiyanantham
1 min readAug 8, 2019

--

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

Originally published at asvignesh.

--

--

Vignesh A Sathiyanantham
Vignesh A Sathiyanantham

Written by Vignesh A Sathiyanantham

Decade of experience in building product related to private datacenter and public cloud #Java #AWS #VMware #Python

No responses yet