Sub topic 3
Reading path variables with @PathVariable
This chapter assumes you can write a Spring Boot controller, you know what a Java record is, and you know HTTP methods and status codes. It covers how a value in the URL path reaches a Java method parameter.
What a path variable is
A path variable is a part of the URL path that changes from one request to the next. In /api/books/42, the 42 identifies one book. You write the variable as a placeholder in curly braces, such as {id}. Spring matches the incoming URL against that template and hands you the value.
Use a path variable when the value identifies a specific resource. The path then reads like a noun: "the book with id 42".
A first example
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping("/{id}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}
}@RequestMapping("/api/books") on the class sets a prefix. @GetMapping("/{id}") adds to it, so the handler serves GET /api/books/{id}. The {id} segment is bound to the id parameter, and Spring converts the string "42" to a Long before calling your method.
You can try it with curl:
curl http://localhost:8080/api/books/42How the binding works
Spring takes these steps for each request:
- It finds the handler whose path template matches the URL.
- It extracts the text for each
{name}placeholder. - It looks for a method parameter annotated with
@PathVariablethat has the same name. - It converts the text to the parameter's type and calls the method.
If step 4 fails, the method is never called. Spring raises an exception and the client gets an error response. Later chapters show how to shape that response.
Matching names
By default, the parameter name must equal the placeholder name. This works because Spring Boot builds with the -parameters compiler flag, which keeps parameter names available at runtime. The Spring Boot Maven and Gradle plugins set this flag for you. If your build does not, binding fails with an error saying the name for the path variable could not be determined.
You can avoid the problem, or use a different Java name, by naming the variable explicitly:
@GetMapping("/{bookId}")
public Book getBook(@PathVariable("bookId") Long id) {
return service.get(id);
}Here the placeholder is bookId and the Java parameter is id.
Several variables in one path
A template can hold more than one placeholder. Each one needs its own parameter.
@GetMapping("/authors/{authorId}/books/{bookId}")
public Book getAuthorBook(@PathVariable Long authorId,
@PathVariable Long bookId) {
return service.getForAuthor(authorId, bookId);
}If you want all of them at once, bind a map:
@GetMapping("/authors/{authorId}/books/{bookId}")
public String show(@PathVariable Map<String, String> vars) {
return vars.get("authorId") + "/" + vars.get("bookId");
}The map holds raw strings, so you lose type conversion. Prefer named parameters.
Optional path variables
A path variable is required by default. If the segment is missing, the URL simply does not match the template and Spring returns 404. You can mark a variable optional with required = false, but this only makes sense when two templates map to the same method:
@GetMapping({"/lookup", "/lookup/{id}"})
public String lookup(@PathVariable(required = false) Long id) {
return id == null ? "no id" : "id " + id;
}When the path is /lookup, id is null. Most of the time, two separate handlers are clearer.
Common errors
| Symptom | Likely cause |
|---|---|
| 400 with a type mismatch message | The segment cannot be converted, such as `/api/books/abc` for a `Long` |
| 404 | The URL has no segment where the template expects one, or the prefix is wrong |
| Startup or request error about the name of the path variable | The `-parameters` flag is missing and no explicit name was given |
| Wrong book returned | Placeholder and parameter names were swapped or mismatched |
Exercises
Exercise
A handler is declared with @GetMapping("/{isbn}") and the method signature is getByIsbn(@PathVariable("isbn") String code). A client calls GET /api/books/978-0441172719. What value does code hold, and why does the name code work?
Show answer
code holds the string "978-0441172719". The explicit name in @PathVariable("isbn") ties the parameter to the {isbn} placeholder, so the Java parameter name does not need to match.
Exercise
A client sends GET /api/books/abc to the getById(@PathVariable Long id) handler. Does getById run? What status does the client receive by default?
Show answer
No. Spring cannot convert "abc" to a Long, so it raises MethodArgumentTypeMismatchException before the method is called. The client receives a 400 Bad Request.