DEV Community

Cover image for Spring - @PathVariable
Yiğit Erkal
Yiğit Erkal

Posted on

Spring - @PathVariable

A Spring annotation called @PathVariable specifies that a method parameter should be tied to a URI template variable.

@GetMapping("/api/products/{id}") @ResponseBody public String getProductsById(@PathVariable String id) { return "ID: " + id; } 
Enter fullscreen mode Exit fullscreen mode

A simple GET request to /api/products/{id} will invoke getProductsById with the extracted id value:

http://localhost:8080/api/products/333 ---- ID: 333 
Enter fullscreen mode Exit fullscreen mode

We may also specify the path variable name:

@GetMapping("/api/products/{id}") @ResponseBody public String getProductsById(@PathVariable("id") String productId) { return "ID: " + productId; } 
Enter fullscreen mode Exit fullscreen mode

One Class to Rule Them All 🪄

Best practice to handle not required path variables is to combine with Java Optional. In this way, you are both able to handle exceptions and the logic.

@GetMapping(value = { "/api/products", "/api/products/{id}" }) @ResponseBody public String getProducts(@PathVariable Optional<String> id) { if (id.isPresent()) { return "ID: " + id.get(); } else { return "ID missing"; } } 
Enter fullscreen mode Exit fullscreen mode

Now if we don't specify the path variable id in the request, we get the default response:

http://localhost:8080/api/employeeswithoptional ---- ID missing 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)