Introduction
Picture this: you’re browsing an e-commerce website and click a link like:
/products?category=books&sort=price&page=1
Even though the endpoint is the same, the results change based on those extra values in the URL. Those are query parameters, and they quietly control how the backend behaves.
In real-world APIs, query parameters are everywhere—filters, pagination, search keywords, feature flags, and more. If you’re learning Spring Boot, knowing how to read query parameters correctly is one of the first skills you must master.
In this blog, you’ll learn how to read query parameters in Spring Boot, explained in a simple, beginner-friendly way with end-to-end Java 21 examples.
Core Concepts
What Are Query Parameters?
Query parameters are optional key–value pairs added to a URL after a ? symbol.
Example:
/users?role=admin&active=true
role=adminactive=true
🧠 Analogy:
Think of an API endpoint as a TV, and query parameters as the remote control buttons. Same TV, different behavior depending on which buttons you press.
How Spring Boot Reads Query Parameters
Spring Boot uses the @RequestParam annotation to:
- Extract values from the URL
- Automatically convert them to Java types
- Handle required, optional, and default values
No manual parsing needed—Spring does the heavy lifting for you.
Common Use Cases
✅ Filtering data (category=books)
✅ Pagination (page=1&size=20)
✅ Sorting (sort=price)
✅ Optional inputs (search, flags, toggles)
Code Examples (End-to-End)
✅ Example 1: Reading Required Query Parameters
Use Case
Fetch users based on role and active status.
Controller Code
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
/**
* Example URL:
* http://localhost:8080/users?role=admin&active=true
*/
@GetMapping
public String getUsers(
@RequestParam String role,
@RequestParam boolean active) {
return "Fetching users with role=" + role + ", active=" + active;
}
}
How This Works
| Request | Result |
|---|---|
/users?role=admin&active=true |
✅ Success |
/users?role=admin |
❌ 400 BAD_REQUEST |
📌 By default, @RequestParam is required.
If the parameter is missing, Spring Boot automatically returns 400 BAD_REQUEST.
✅ Example 2: Optional Query Parameters with Defaults (Real-World API)
Use Case
Search products with optional filters and pagination.
Controller Code
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/products")
public class ProductController {
/**
* Example URLs:
* /products
* /products?category=laptop
* /products?category=laptop&page=1&size=10
*/
@GetMapping
public String searchProducts(
@RequestParam(required = false) String category,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return String.format(
"Searching products [category=%s, page=%d, size=%d]",
category, page, size
);
}
}
Behavior Explained
| URL | Output |
|---|---|
/products |
category=null, page=0, size=20 |
/products?category=laptop |
page=0, size=20 |
/products?page=2&size=5 |
category=null |
✔ Optional params don’t break the API
✔ Defaults prevent unnecessary errors
✔ Clean and flexible design
🧠 Bonus: Reading Dynamic Query Parameters
@GetMapping("/search")
public String search(@RequestParam Map<String, String> params) {
return "Query parameters received: " + params;
}
Useful when:
- Filters are dynamic
- You don’t know all params in advance
- Building search APIs
Best Practices
Use query parameters for optional inputs
Mandatory identifiers belong in path variables.Always provide default values for pagination
Prevents accidental400 BAD_REQUEST.Use meaningful parameter names
pageis better thanp.Validate query parameters
Combine with@Validatedand constraints like@Min.Avoid overloading endpoints
Too many query params may signal a need for a request body.
Conclusion
Reading query parameters is a core building block of REST APIs in Spring Boot.
With @RequestParam, you can:
- Read values safely
- Handle optional inputs
- Build flexible, user-friendly APIs
Mastering reading query parameters in Spring Boot will greatly improve your confidence in Java programming and help you learn Java with real-world, production-ready patterns.
Call to Action
💬 Have questions about query parameters or REST API design?
👇 Drop them in the comments!
🔗 Helpful Resources
Top comments (0)