DEV Community

Cover image for Difference Between @PathVariable and @RequestParam
Arul .A
Arul .A

Posted on

Difference Between @PathVariable and @RequestParam

Both @PathVariable and @RequestParam are used to receive data from the client request in Spring Boot.But they work in completely different ways.

What is @PathVariable?

  • @PathVariable is used to get values directly from the URL path.

Example:

@GetMapping("/product/{id}")
public String getProduct(@PathVariable int id) {
    return "Product ID: " + id;
}
Enter fullscreen mode Exit fullscreen mode

URL:

/product/10

Here:

id = 10 => The value 10 becomes part of the URL path itself.

Usually used for:

  • Specific resource IDs
  • Mandatory values
  • Unique objects

  • What is @RequestParam?

@RequestParam gets values from query parameters.

Example:

@GetMapping("/products")
public String search(@RequestParam String category) {
    return category;
}
Enter fullscreen mode Exit fullscreen mode

URL:

/products?category=mobile

Here:

category = "mobile"

Usually used for:

  • Filtering
  • Searching
  • Sorting
  • Pagination
  • Optional data

Examples:

/products?category=mobile
/products?page=2
/products?sort=price
/products?search=iphone
Enter fullscreen mode Exit fullscreen mode

These are not unique resources.

They are conditions or filters.

Top comments (0)