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; }
A simple GET request to /api/products/{id} will invoke getProductsById with the extracted id value:
http://localhost:8080/api/products/333 ---- ID: 333
We may also specify the path variable name:
@GetMapping("/api/products/{id}") @ResponseBody public String getProductsById(@PathVariable("id") String productId) { return "ID: " + productId; }
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"; } }
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
Top comments (0)