@PathVariable lets you get parts of the URL as variables in your code. This helps your app respond differently based on the URL.
@PathVariable for URL parameters in Spring Boot
@GetMapping("/path/{variableName}")
public ReturnType methodName(@PathVariable Type variableName) {
// use variableName here
}The part in curly braces {} in the URL is the variable name.
The method parameter annotated with @PathVariable must match the variable name in the URL.
@GetMapping("/user/{id}") public String getUser(@PathVariable String id) { return "User ID: " + id; }
@GetMapping("/order/{orderId}/item/{itemId}") public String getOrderItem(@PathVariable int orderId, @PathVariable int itemId) { return "Order: " + orderId + ", Item: " + itemId; }
@GetMapping("/product/{name}") public String getProduct(@PathVariable(name = "name") String productName) { return "Product: " + productName; }
This simple Spring Boot controller has one URL endpoint /user/{id}. When you visit /user/45, it returns 'User ID received: 45'.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @GetMapping("/user/{id}") public String getUserById(@PathVariable String id) { return "User ID received: " + id; } }
If the method parameter name matches the path variable name, you can omit the name attribute in @PathVariable.
Path variables are always strings but Spring can convert them to other types like int or long automatically.
Use @PathVariable only for parts of the URL path, not for query parameters (use @RequestParam for those).
@PathVariable extracts values from the URL path.
It helps create dynamic and readable URLs.
Use it in Spring Boot controller methods with @GetMapping or other mapping annotations.