Sub topic 3
Reading path variables with @PathVariable
A path variable is a part of the URL path that identifies a resource, such as the 42 in /api/books/42. This chapter covers how @PathVariable binds that segment to a method parameter, and how to handle names, multiple variables, optional segments, patterns, and failures.
It assumes you have a running Spring Boot 3 web project, you know what a controller class is, and you know the basic HTTP concepts of methods and status codes. Request mappings get a short recap here. Type conversion and error handling each get their own later chapter, so this one covers only what you need for path variables.
What a path variable is
In a mapping, a URI template is a path with placeholders in curly braces. Spring matches the incoming path against the template and extracts the text at each placeholder. @PathVariable hands that text to a method parameter.
@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);
}
}For a request to GET /api/books/42, the class-level /api/books and the method-level /{id} combine into /api/books/{id}. Spring extracts the string "42", converts it to a Long, and calls getById(42L).
The next diagram shows the steps Spring takes for each request.
How the name is matched
Spring matches the placeholder name to the parameter name. In /{id} with Long id, both are id.
If the names differ, give the placeholder name explicitly. Use the name attribute, or the value attribute, which means the same thing.
@GetMapping("/{bookId}")
public Book getById(@PathVariable("bookId") Long id) {
return service.get(id);
}Without an explicit name, Spring reads the parameter name from the compiled class. This works only if the code was compiled with the -parameters flag. The Spring Boot Maven and Gradle plugins set that flag for you, so it usually just works. In a build that does not set the flag, Spring 6.1 and later fail the request with an IllegalArgumentException that says the name for the argument could not be determined. If you see that error, either fix the compiler setting or write the name explicitly.
Several path variables
A template can have 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);
}A request to /api/books/authors/7/books/42 binds authorId to 7 and bookId to 42. Hierarchical URLs like this express that one resource belongs to another. The service should still check that book 42 belongs to author 7. The URL does not enforce that relationship.
Getting all path variables at once
For generic code, such as logging or a handler that serves many templates, you can bind every variable to a Map<String, String>. Values stay as strings, and no conversion happens.
@GetMapping("/authors/{authorId}/books/{bookId}")
public String describe(@PathVariable Map<String, String> vars) {
return "author=" + vars.get("authorId") + ", book=" + vars.get("bookId");
}Prefer individual typed parameters when you can. The map gives up type conversion and makes the method's needs less clear from its signature.
Types other than numbers
Conversion works for any type Spring knows how to build from a string. That includes numbers, UUID, and enums.
public enum Genre { FANTASY, SCIENCE_FICTION, HISTORY }
@GetMapping("/genres/{genre}")
public List<Book> byGenre(@PathVariable Genre genre) {
return service.findByGenre(genre);
}A request to /api/books/genres/FANTASY works. For enums, the match is case-sensitive by default, so /genres/fantasy fails conversion and produces a 400 response. Decide whether that strictness is acceptable for your API. If it is not, accept a String and convert it yourself, or register a custom converter. A later chapter covers converters.
Optional path variables
A path variable is required by default. If the placeholder is in the template, the segment must be present, or the template does not match at all.
To make a segment optional, map the same method to two templates and mark the variable as not required.
@GetMapping({"/authors/{authorId}/books", "/authors/{authorId}/books/{bookId}"})
public Object authorBooks(@PathVariable Long authorId,
@PathVariable(required = false) Long bookId) {
if (bookId == null) {
return service.booksOf(authorId);
}
return service.getForAuthor(authorId, bookId);
}This works, but the return type is now Object, and one method does two jobs. Two separate methods are usually clearer. You can also use Optional<Long> as the parameter type, which has the same effect as required = false.
Restricting a variable with a regular expression
A placeholder can carry a regular expression after a colon. The template matches only when the segment fits the expression.
@GetMapping("/{id:\\d+}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}
@GetMapping("/{slug:[a-z-]+}")
public Book getBySlug(@PathVariable String slug) {
return service.getBySlug(slug);
}With these two mappings, /api/books/42 goes to the first method and /api/books/dune-messiah goes to the second. Without the expressions, both templates would match both paths, and Spring would report an ambiguous mapping.
There is a trade-off. With {id:\\d+}, a request to /api/books/abc matches no template, so it returns 404 instead of the 400 you would get from a failed conversion. Use a regular expression when you need to tell templates apart. Do not use one only to validate input, because a 400 with a clear message is more useful to the caller than a 404.
What happens when it goes wrong
Three failures are common. The table shows where each one comes from.
| Request | Cause | Result |
|---|---|---|
| `GET /api/books/abc` with `Long id` | The text cannot be converted to a number | 400, from `MethodArgumentTypeMismatchException` |
| `GET /api/books/` with only `/{id}` mapped | The segment is empty, so no template matches | 404 |
| `GET /api/books/99999` and no such book | Conversion succeeded, but no record exists | Whatever your code decides |
The third row is the one people forget. Spring only binds the value. It does not check that the resource exists. Your service has to do that and signal the result. A simple way is to throw ResponseStatusException.
@GetMapping("/{id}")
public Book getById(@PathVariable Long id) {
return service.find(id).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND,
"No book with id " + id));
}A later chapter shows how to produce 400 responses in a consistent format with @RestControllerAdvice. By default Spring Boot already returns a 400 for a conversion failure, but the body is generic.
Edge cases to know about
- Trailing slashes. Since Spring 6,
/api/books/42/does not match/api/books/{id}. Older versions matched both. If you upgrade from Spring 5 and clients break, this is a likely cause. - Dots in the value. Older versions treated
/books/1.jsonas a request for/books/1in JSON format. That suffix matching is off now, so{id}receives1.jsonwhole. A value that contains a dot, such as an email address, therefore works. - Slashes in the value. A placeholder matches a single path segment and never contains
/. To capture the rest of a path, use a capture-all placeholder such as{*path}, which gives you the remaining segments including the leading slash. - Encoding. Spring decodes URL-encoded values before binding. A request to
/api/books/genres/SCIENCE%5FFICTIONarrives asSCIENCE_FICTION. - Sensitive identifiers. A path variable comes from the caller and can be anything. Do not assume a client may read book 42 just because it asked for it. Check authorization on the resource, not only on the endpoint.
Trying it
Use curl to see each outcome from your running application.
curl -i http://localhost:8080/api/books/42
curl -i http://localhost:8080/api/books/abc
curl -i http://localhost:8080/api/books/genres/FANTASYThe first returns 200 if book 42 exists, or 404 if your service says it does not. The second returns 400 because abc is not a Long. The third shows enum binding.
Summary
@PathVariablebinds a{placeholder}from the mapping to a parameter, matched by name.- Give the name explicitly when the Java parameter name differs, or when you cannot rely on the
-parameterscompiler flag. - Conversion supports numbers,
UUID, enums, and other types, and a failed conversion gives 400. - A variable is required unless you map several templates and set
required = false. - A regular expression in the placeholder can distinguish templates, but a mismatch returns 404.
- Spring binds the value but does not check that the resource exists.
Exercise
A controller has @GetMapping("/{id:\\d+}") with a Long id parameter. A client requests GET /api/books/abc. What status code does it get, and how does it differ from the same request when the mapping is just /{id}?
Show answer
With the regular expression, abc does not match the template, so no handler is found and the response is 404. With plain /{id}, the template matches and Spring tries to convert abc to a Long. That fails with a MethodArgumentTypeMismatchException, which gives 400. Use the plain template when you want the more informative 400.
Exercise
You write @GetMapping("/{bookId}") public Book get(@PathVariable Long id). Why does this fail, and give two ways to fix it.
Show answer
The placeholder is bookId but the parameter is named id, so Spring finds no variable called id (or cannot determine the name). Fix it by renaming the parameter to bookId, or by writing @PathVariable("bookId") Long id. Renaming the placeholder to {id} also works.
Exercise
Which of these needs your own code and not Spring: converting "42" to a Long, returning 404 when book 42 does not exist, or extracting 42 from /api/books/42?
Show answer
Returning 404 for a missing book. Spring extracts and converts the value, but it has no way to know whether a record exists, so your code must check that and signal the result, for example with ResponseStatusException.