AI Hints
Home›Spring Boot Tutorial›Path Variables, Query Parameters and Practice: A Greeting API
Spring Boot · Lesson 16 of 120

Path Variables

Values inside the URL.

⏱ 2 min read▶ Video at 20:50🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Often, part of the URL is a value. Slash books slash one, slash books slash two. We don't want a method for every number. We want one method, that reads the number.

  • /books/1, /books/2 ...
  • One method for all
  • Read the value

How it works

In the mapping, curly braces mark a variable part, like id. At Path Variable on a parameter, receives that part of the URL. The names must match, id and id. And Spring converts the text into the parameter's type, like int.

keyvalue
Mapping"/books/{id}"
Parameter@PathVariable int id
Namesmust match
Typetext → int for you

Reading the id

The mapping has a variable called id. At Path Variable int id receives it, already as a number. We check the range, then return the matching title. Run it. Book one is Dune, and book three is Circe. Nine is out of range, so we say so. And abc isn't a number, so Spring answers four hundred, bad request.

BookController.javajava
@RestController
public class BookController {

    private final List<String> titles = List.of("Dune", "The Hobbit", "Circe");

    @GetMapping("/books/{id}")
    public String book(@PathVariable int id) {
        if (id < 1 || id > titles.size()) {
            return "No book with id " + id;
        }
        return "Book " + id + ": " + titles.get(id - 1);
    }
}
Output
$ curl localhost:8080/books/1
Book 1: Dune
$ curl localhost:8080/books/3
Book 3: Circe
$ curl localhost:8080/books/9
No book with id 9
$ curl -i localhost:8080/books/abc | head -1
HTTP/1.1 400
Also uses _curl.sh
curl localhost:8080/books/1
curl localhost:8080/books/3
curl localhost:8080/books/9
curl -i localhost:8080/books/abc | head -1

Two variables

A path can hold several variables. Here, the author, and a year. Each gets its own at Path Variable. Run it. Both values are read from the URL.

BookController.javajava
@RestController
public class BookController {

    @GetMapping("/authors/{author}/books/{year}")
    public String byAuthor(@PathVariable String author, @PathVariable int year) {
        return "Books by " + author + " from " + year;
    }
}
Output
Books by tolkien from 1937
Also uses _curl.sh
curl localhost:8080/authors/tolkien/books/1937

Summary

Curly braces in the mapping mark a variable, and at Path Variable reads it, converted to the right type. Next, query parameters.

Key takeaways
  • /books/{id}
  • @PathVariable int id
  • Wrong type → 400
Next up: Query Parameters — ?name=value