We use path variables and query parameters together to get specific and flexible information from a web request. Path variables identify a resource, and query parameters filter or add details.
Handling path variables and query params together in Spring Boot
@GetMapping("/resource/{id}")
public ResponseEntity<?> methodName(@PathVariable Type id, @RequestParam(required = false) Type param) {
// method body
}@PathVariable extracts values from the URL path.
@RequestParam extracts query parameters from the URL after the question mark.
@GetMapping("/users/{userId}") public String getUser(@PathVariable String userId, @RequestParam(required = false) String filter) { return "User: " + userId + ", Filter: " + filter; }
@GetMapping("/products/{category}") public String getProducts(@PathVariable String category, @RequestParam(defaultValue = "asc") String sort) { return "Category: " + category + ", Sort: " + sort; }
This Spring Boot controller has a method that takes an item ID from the URL path and an optional color from the query parameters. It returns a simple string showing both values.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ItemController { @GetMapping("/items/{itemId}") public String getItemDetails(@PathVariable String itemId, @RequestParam(required = false) String color) { if (color == null) { return "Item ID: " + itemId + ", Color: not specified"; } return "Item ID: " + itemId + ", Color: " + color; } }
If a query parameter is optional, set required = false to avoid errors when it's missing.
You can provide default values for query parameters using defaultValue in @RequestParam.
Path variables are part of the URL structure, while query parameters come after a question mark and can be many or none.
Use @PathVariable to get parts of the URL path.
Use @RequestParam to get query parameters after the URL path.
Combining both lets you build flexible and clear web endpoints.
Practice
Solution
Step 1: Understand URL parts
The URL path segment is the part of the URL that defines the resource location, like /users/{id}.Step 2: Identify the correct annotation
@PathVariable is used to bind a method parameter to a URI template variable in the path.Final Answer:
@PathVariable -> Option AQuick Check:
Path segment value = @PathVariable [OK]
- Confusing @RequestParam with @PathVariable
- Using @RequestBody for path variables
- Trying to get path variables from headers
id and a query parameter sort in Spring Boot?Solution
Step 1: Match annotations to parameter types
Path variables come from the URL path, so use @PathVariable forid. Query parameters come after ?, so use @RequestParam forsort.Step 2: Check method signature correctness
public String getUser(@PathVariable String id, @RequestParam String sort) correctly uses @PathVariable foridand @RequestParam forsort.Final Answer:
public String getUser(@PathVariable String id, @RequestParam String sort) -> Option AQuick Check:
Path variable = @PathVariable, Query param = @RequestParam [OK]
- Swapping @PathVariable and @RequestParam
- Using @PathVariable for query parameters
- Missing one of the annotations
@GetMapping("/items/{itemId}")
public String getItem(@PathVariable String itemId, @RequestParam(defaultValue = "asc") String order) {
return itemId + "-" + order;
}What will be the output when a client requests
/items/42?order=desc?Solution
Step 1: Identify values from URL
Path variableitemIdis "42" from /items/42. Query parameterorderis "desc" from ?order=desc.Step 2: Understand method return
The method returnsitemId + "-" + order, so "42-desc".Final Answer:
"42-desc" -> Option BQuick Check:
Path variable + query param = "42-desc" [OK]
- Ignoring query parameter and using default
- Mixing order of concatenation
- Expecting error when query param is present
@GetMapping("/books/{bookId}")
public String getBook(@PathVariable int bookId, @RequestParam int page) {
return "Book: " + bookId + ", Page: " + page;
}What error will occur if a client calls
/books/abc?page=2?Solution
Step 1: Check path variable type
The method expectsbookIdas int, but URL provides "abc" which is not a number.Step 2: Understand Spring Boot behavior on type mismatch
Spring Boot returns 400 Bad Request when it cannot convert path variable to required type.Final Answer:
400 Bad Request due to type mismatch -> Option CQuick Check:
Type mismatch in @PathVariable causes 400 error [OK]
- Expecting 404 Not Found instead of 400
- Assuming null page causes error
- Thinking method returns string with invalid input
filter. If filter is missing, it should default to "all". Which method signature correctly implements this behavior?Solution
Step 1: Identify path variable usage
User ID is part of the URL path, so use @PathVariable foruserId.Step 2: Handle optional query parameter with default
Use @RequestParam withdefaultValue = "all"to provide a default whenfilteris missing.Final Answer:
public String getUser(@PathVariable String userId, @RequestParam(defaultValue = "all") String filter) -> Option DQuick Check:
Default query param value = @RequestParam(defaultValue) [OK]
- Using @RequestParam(required = true) for optional params
- Using @RequestParam without defaultValue causing errors
- Confusing @RequestParam and @PathVariable roles
Ready to prove it?
Pass the test and this pattern moves unknown
