Sub topic 5
Reading path variables and query parameters
This chapter assumes you can write a basic @RestController, know the @GetMapping family of annotations, and understand HTTP methods and status codes. It covers how Spring MVC copies values from the URL into method arguments.
Two places for data in a URL
A URL can carry data in two places:
- The path identifies a specific resource:
/api/books/42. - The query string refines or filters a request:
/api/books?title=dune.
A rule of thumb: use a path variable to say which resource, and a query parameter to say how to list, filter, or sort resources.
Path variables
A path variable is a named segment in the URL template. Declare it in braces and bind it with @PathVariable.
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}Spring matches the argument to the {id} placeholder by name. It also converts the text "42" to a long. If the text cannot be converted, for example /api/books/abc, Spring rejects the request with a 400 Bad Request before your method runs.
If the placeholder and the argument have different names, name the variable explicitly:
@GetMapping("/{bookId}")
public BookResponse get(@PathVariable("bookId") long id) {
return service.get(id);
}Name-based matching relies on parameter names being kept in the compiled class. Spring Boot's Maven and Gradle plugins configure this for you. In other builds, compile with -parameters or always use the explicit form.
Query parameters
Bind query parameters with @RequestParam. Here is the full controller from this chapter.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<BookResponse> list(@RequestParam(defaultValue = "") String title) {
return service.search(title);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
}Both methods share the /api/books prefix from the class-level @RequestMapping. The list method handles GET /api/books?title=dune. The get method handles GET /api/books/42.
Required, optional, and default values
By default, @RequestParam is required. If the client omits it, Spring returns 400 Bad Request. You have three ways to change that.
| Declaration | Behavior when the parameter is missing |
|---|---|
| `@RequestParam String title` | `400 Bad Request` |
| `@RequestParam(required = false) String title` | `title` is `null` |
| `@RequestParam Optional<String> title` | `title` is `Optional.empty()` |
| `@RequestParam(defaultValue = "") String title` | `title` is `""` |
Setting defaultValue makes the parameter optional automatically. The default is also used when the parameter is present but empty, as in ?title=.
@PathVariable is also required by default. Because the path template must match for the method to be chosen at all, a missing path variable normally means a different handler (or a 404).
Type conversion
Spring converts both kinds of value from text to the declared type. It handles numbers, booleans, enums, UUID, and dates (with @DateTimeFormat). Repeated parameters, as in ?tag=a&tag=b, can bind to a List<String>.
@GetMapping("/search")
public List<BookResponse> search(
@RequestParam List<String> tag,
@RequestParam(defaultValue = "true") boolean inStock) {
return service.findByTags(tag, inStock);
}A value that cannot be converted, such as ?inStock=maybe, produces a 400 response.
How the binding happens
Common mistakes
- Using a primitive for an optional parameter. With
@RequestParam(required = false) int page, a missing value cannot becomenull, and Spring raises an error. UseInteger,Optional<Integer>, or adefaultValue. - Putting filters in the path.
/api/books/dunecollides with/api/books/{id}in meaning. Keep filters in the query string. - Forgetting that names must match. A typo between the template and the argument name causes an error at request time, not at startup.
Exercise
A client calls GET /api/books?title=dune on a method declared as list(@RequestParam String title, @RequestParam int page). What status code does it receive, and why?
Show answer
It receives 400 Bad Request. Both parameters are required by default, and page is missing from the query string. Adding defaultValue = "0" to page would make the call succeed.
Exercise
Which would you use for each: selecting one book by its ID, and listing books whose author is "Herbert"?
Show answer
Use a path variable for the ID (/api/books/{id} with @PathVariable). Use a query parameter for the author filter (/api/books?author=Herbert with @RequestParam).