Path Variables & Request Params
Clients pass small pieces of input in the URL itself. Path variables identify which resource (/api/tasks/42), and query parameters describe how to return it — filters, search terms, page numbers (/api/tasks?done=false&tag=work). Spring converts both from strings to the Java types your method declares.
@PathVariable
@RestController
@RequestMapping("/api")
class ProjectController {
@GetMapping("/tasks/{id}")
Task task(@PathVariable long id) { ... }
@GetMapping("/projects/{projectId}/tasks/{taskId}")
Task taskInProject(@PathVariable long projectId, @PathVariable long taskId) { ... }
@GetMapping("/users/{username:[a-z0-9_]{3,20}}") // regex constraint
User user(@PathVariable String username) { ... }
}The variable name in {...} must match the parameter name. That works because Spring Boot compiles with -parameters; otherwise write @PathVariable("id") long id.
@RequestParam
@GetMapping("/tasks")
List<Task> search(
@RequestParam(required = false) String q, // optional, null if absent
@RequestParam(defaultValue = "false") boolean done, // default
@RequestParam(name = "tag", required = false) List<String> tags, // ?tag=a&tag=b
@RequestParam Optional<Integer> limit) { // Optional = not required
...
}| Declaration | ? missing |
Notes |
|---|---|---|
@RequestParam String q |
400 Bad Request | required by default |
@RequestParam(required = false) String q |
null |
|
@RequestParam(defaultValue = "10") int size |
10 |
implies not required |
@RequestParam Optional<Integer> limit |
Optional.empty() |
|
@RequestParam List<String> tag |
400 | repeated params ?tag=a&tag=b or ?tag=a,b |
@RequestParam Map<String,String> all |
empty map | every query parameter |
curl -s "localhost:8080/api/tasks?q=spring&done=false&tag=work&tag=urgent"
echo
curl -s "localhost:8080/api/tasks/abc"[{"id":3,"title":"Read the Spring docs","done":false,"tags":["work","urgent"]}]
{"timestamp":"2025-10-16T03:44:51.102+00:00","status":400,"error":"Bad Request","path":"/api/tasks/abc"}
abc cannot be converted to long, so Spring rejects the request with 400 before your method is called — you never see a NumberFormatException in your own code.
How Spring extracts and converts
The following program does what Spring does for one request: match the template, collect the variables, parse the query string, then convert each value to the declared type:
import java.util.*;
class Main {
static Map<String, String> pathVariables(String template, String path) {
String[] t = template.split("/"), p = path.split("/");
if (t.length != p.length) return null;
Map<String, String> vars = new LinkedHashMap<>();
for (int i = 0; i < t.length; i++) {
if (t[i].startsWith("{")) vars.put(t[i].substring(1, t[i].length() - 1), p[i]);
else if (!t[i].equals(p[i])) return null;
}
return vars;
}
static Map<String, List<String>> queryParams(String query) {
Map<String, List<String>> params = new LinkedHashMap<>();
for (String pair : query.split("&")) {
String[] kv = pair.split("=", 2);
params.computeIfAbsent(kv[0], k -> new ArrayList<>()).add(kv.length > 1 ? kv[1] : "");
}
return params;
}
public static void main(String[] args) {
String url = "/api/projects/7/tasks/42?done=true&tag=work&tag=urgent";
String path = url.substring(0, url.indexOf('?'));
String query = url.substring(url.indexOf('?') + 1);
Map<String, String> vars = pathVariables("/api/projects/{projectId}/tasks/{taskId}", path);
Map<String, List<String>> params = queryParams(query);
System.out.println("path variables: " + vars);
System.out.println("query params: " + params);
long projectId = Long.parseLong(vars.get("projectId"));
long taskId = Long.parseLong(vars.get("taskId"));
boolean done = Boolean.parseBoolean(params.get("done").get(0));
List<String> tags = params.getOrDefault("tag", List.of());
int limit = Integer.parseInt(params.getOrDefault("limit", List.of("20")).get(0));
System.out.printf("handler(projectId=%d, taskId=%d, done=%b, tags=%s, limit=%d)%n",
projectId, taskId, done, tags, limit);
try {
Long.parseLong(pathVariables("/api/tasks/{id}", "/api/tasks/abc").get("id"));
} catch (NumberFormatException e) {
System.out.println("-> 400 Bad Request (" + e.getMessage() + ")");
}
}
}path variables: {projectId=7, taskId=42}
query params: {done=[true], tag=[work, urgent]}
handler(projectId=7, taskId=42, done=true, tags=[work, urgent], limit=20)
-> 400 Bad Request (For input string: "abc")
Converting to richer types
Spring's conversion service supports enums, dates and your own types:
enum Priority { LOW, MEDIUM, HIGH }
@GetMapping("/tasks/due")
List<Task> due(@RequestParam Priority priority, // ?priority=HIGH
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate before) { // ?before=2025-12-31
...
}Enum values are matched by their constant name (?priority=HIGH). An unknown value such as ?priority=URGENT fails conversion and produces a 400 response, just like a malformed number.
Binding many parameters to a record
When an endpoint has many filters, collect them into a record. Without an annotation, Spring binds query parameters to the record's constructor by name:
record TaskFilter(String q, Boolean done, List<String> tag, Integer limit) {}
@GetMapping("/tasks")
List<Task> search(TaskFilter filter) {
return service.search(filter);
}curl -s "localhost:8080/api/tasks?done=true&limit=1"[{"id":2,"title":"Write a controller","done":true,"tags":[]}]
Path variable or query parameter?
| Use a path variable for... | Use a query parameter for... |
|---|---|
identity: /tasks/42 |
filtering: ?done=false |
hierarchy: /projects/7/tasks |
searching: ?q=spring |
| required values | optional values with defaults |
paging and sorting: ?page=2&sort=title |
Tip: URL-encode user input in query strings: a space becomes
%20(or+),&becomes%26. Spring decodes the values for you before binding.
Test yourself
What does Spring return for GET /api/tasks/abc when the handler declares @PathVariable long id?
- 500 with a NumberFormatException
- 400 Bad Request
- 404 Not Found
- It passes 0
Which declaration makes a query parameter optional with value null when it is missing?
@RequestParam String q@RequestParam(required = false) String q@PathVariable String q@RequestParam(defaultValue = "") String q
Which is the best URL for 'tasks of project 7 that are not done'?
/api/getTasks?project=7&done=false/api/projects/7/tasks?done=false/api/tasks/notDone/7/api/projects/tasks/7/false