@PathVariable in Spring MVC — Extracting URL Path Segments
Fast recall
Quick revision
Core answer
Understanding of REST URL parameter extraction and how Spring MVC binds path segments to method parameters
Using @RequestParam for resource identifiers like user ID instead of @PathVariable, which breaks REST conventions and makes URLs look like /users?id=42 instead of /users/42
Explain the REST design principle that path variables represent resource identity (the 'what') while query params represent filtering or options (the 'how')
Interview-ready guide
Interview answer
@GetMapping("/users/{id}") UserDto find(@PathVariable long id) binds /users/42. If the Java parameter name is unavailable or different, use @PathVariable("id"). A missing segment such as /users does not call this method because it is a different path pattern. An invalid long such as /users/abc reaches conversion failure if the route pattern otherwise matches.
@PathVariable in Spring MVC — Extracting URL Path Segments
Direct Answer
@PathVariable binds a value captured from a request-mapping URI template. For @GetMapping("/users/{id}"), a request to /users/42 binds id to 42 and Spring converts it to the declared parameter type. Path variables commonly identify resources, but route design—not the annotation—decides their business meaning.
Code Example
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/{userId}")
public User getUserById(@PathVariable Long userId) {
// Spring extracts userId from /api/users/42 -> userId = 42
return userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found"));
}
@GetMapping("/{userId}/orders/{orderId}")
public Order getUserOrder(@PathVariable Long userId,
@PathVariable Long orderId) {
// Multiple path variables: /api/users/10/orders/250
return userRepository.findOrderByUserAndId(userId, orderId)
.orElseThrow(() -> new ResourceNotFoundException("Order not found"));
}
}
Common Mistakes & Pitfalls
- Using @RequestParam for resource IDs: Freshers often write
@GetMapping("/users")with@RequestParam Long id, resulting in/users?id=42instead of the RESTful/users/42. This breaks REST conventions and makes URLs harder to read and cache. - Forgetting type conversion errors: If a client sends
/users/abcwhereabccan't convert toLong, Spring throwsMethodArgumentTypeMismatchException. Freshers forget to handle this with@ExceptionHandlerand return a proper 400 Bad Request. - Naming mismatches: When the path variable name differs from the parameter name, you must specify it:
@PathVariable("userId") Long id. Freshers forget the annotation parameter and get binding errors.
Check your understanding
Answer these without looking back at the article.
- What is the difference between @PathVariable and @RequestParam?
- How do you add regex constraint to a @PathVariable?
- What happens if the path variable cannot be converted to the parameter type?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.