Learn how to use @RequestParam in Spring Boot to handle query parameters effectively with practical examples from real-world scenarios like search, filtering, and pagination.
What is @RequestParam
@RequestParam is a Spring Boot annotation used to bind query parameters from the URL to method parameters in a controller. Unlike @PathVariable, which is used for identifying resources, @RequestParam is mainly used for filtering, searching, and optional data inputs.
@RequestParamis used in Spring Boot to extract query parameters from the URL and bind them to method parameters for filtering, searching, or optional inputs in REST APIs.
For example, /products?category=books&price=500 uses query parameters to filter results. It is widely used in real-world applications like e-commerce for search functionality, pagination, and sorting. It also supports optional values, default values, and multiple inputs. This makes APIs more flexible without changing the endpoint structure, improving usability and scalability in production systems.
In Spring Boot, @RequestParam is used to extract values from query parameters in the URL. It is commonly used when you want to pass optional or filtering data to your APIs without changing the URL structure.
Let’s start with a simple example:
@GetMapping("/users")
public String getUserById(@RequestParam Long userId) {
return "User ID: " + userId;
}
When a request like /users?userId=101 is made, Spring maps 101 to the userId parameter.
Now consider a real-world e-commerce scenario where users search for products:
@GetMapping("/products")
public String searchProducts(@RequestParam String category,
@RequestParam String sortBy) {
return "Category: " + category + ", Sort By: " + sortBy;
}
Example request: /products?category=electronics&sortBy=price
You can also make parameters optional:
@GetMapping("/products")
public String getProducts(@RequestParam(required = false) String category) {
return "Category: " + category;
}
Or provide default values:
@GetMapping("/products")
public String getProducts(
@RequestParam(defaultValue = "all") String category) {
return "Category: " + category;
}
For multiple values:
@GetMapping("/products/filter")
public String filterProducts(@RequestParam List<String> tags) {
return "Tags: " + tags;
}
In real-world systems like CRM or booking platforms, @RequestParam is used for filtering data such as date ranges, status, pagination (page, size), or sorting options.
Best practices include keeping query parameters meaningful, using default values for better UX, validating inputs, and avoiding too many parameters in a single API.
Using @RequestParam properly helps build flexible, scalable, and user-friendly APIs aligned with REST standards.



