When designing RESTful APIs, we often need to extract data directly from the URL path, such as IDs or names, to handle specific resources. Without @PathVariable
, extracting these dynamic parts from the URL would be cumbersome.
What is it?
@PathVariable
is an annotation in Spring MVC used to extract values from the URL path and bind them to method parameters. This is useful when you want to access dynamic parts of the URL, such as user IDs or resource names.
How is it used?
You place @PathVariable
in the method parameter list to capture parts of the URL.
Example:
@GetMapping("/users/{id}") public User getUserById(@PathVariable("id") Long userId) { return userService.findUserById(userId); }
In this example, when a GET request is made to /users/5
, the value 5
is captured and passed as the userId
parameter to the getUserById()
method.
Key points:
- The value inside the {}
in the URL must match the parameter name, or you can explicitly specify it in the annotation.
- You can use multiple @PathVariable
s for more complex URLs.
@PathVariable
is particularly useful for retrieving dynamic data directly from the URL, making APIs more intuitive and resource-focused.