Spring provides two options to mark a REST parameter as optional:
- Use
required = false
in the @PathVariable
or @RequestParam
annotation of the respective method parameter
or
- Use type
java.util.Optional<T>
for the method parameter
When using 1., the absence of the parameter, when the REST function is called, is encoded by null
, which can only be used for object
types. If required = false
is used for a parameter with a primitive and the REST function is called without the parameter, a runtime
exception occurs because the Spring data mapper cannot map the null
value to the parameter.