Explain the difference between request param and path variable

Key Differences Between @RequestParam and @PathVariable

1. Purpose:

  • @RequestParam: Used to extract query parameters from the URL.
  • @PathVariable: Used to extract values from the URI path.

2. Usage Context:

  • @RequestParam: Typically used when parameters are passed as query strings in the URL.
  • @PathVariable: Typically used when values are embedded directly in the URI path.

Example Scenarios

Example 1: Using @RequestParam

  • Scenario:

You have an endpoint that filters users based on a query parameter. * URL: http://example.com/users?name=John * Controller Method:

@RestController
public class UserController {

@GetMapping("/users")
public List<User> getUsersByName(@RequestParam String name) {
// Logic to retrieve users by name
return userService.findUsersByName(name);
}


}  

Explanation:

- @RequestParam is used to extract the query parameter name from the URL.

- The value of name is passed to the getUsersByName method.

Example 2: Using @PathVariable

  • Scenario:

You have an endpoint that retrieves a user by their ID embedded in the URL path. * URL: http://example.com/users/123 * Controller Method:

@RestController
public class UserController {

@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
// Logic to retrieve user by ID
return userService.findUserById(id);
}


}  

Explanation:

- @PathVariable is used to extract the id variable from the URI path.

- The value of id is passed to the getUserById method.


Conclusion

Understanding the differences between @RequestParam and @PathVariable allows you to design your Spring Boot application's endpoints more effectively, ensuring that parameters are mapped to method arguments correctly based on their context in the URL. Use @RequestParam for query parameters and @PathVariable for path variables to achieve clear and efficient URL mapping in your RESTful APIs.