DEV Community

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

Posted on

7 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay