Both @PathVariable and @RequestParam are Spring annotations used to extract values from an HTTP request, but they serve different purposes:

@PathVariable

  • Purpose: Extracts values from the URI path (dynamic segments).
  • Use Case: When you need to capture a part of the URL.
  • Example:

    @GetMapping("/users/{id}")
    public String getUserById(@PathVariable String id) {
        return "User ID: " + id;
    }
    // URL: /users/123 → id = "123"
    

@RequestParam

  • Purpose: Extracts values from query parameters in the URL.
  • Use Case: When you want to capture data passed after ? in the URL.
  • Example:

    @GetMapping("/search")
    public String search(@RequestParam String keyword) {
        return "Search for: " + keyword;
    }
    // URL: /search?keyword=Spring → keyword = "Spring"
    

Key Difference

  • @PathVariable: Maps to a URI segment.
  • @RequestParam: Maps to query parameters.

Use @RequestParam for optional inputs and @PathVariable for mandatory identifiers!