Path variables usually identify one thing, like book number three. Query parameters usually filter, sort, or adjust results, like search, or limit. Query parameters are often optional, path variables are not.
At Request Param reads a query parameter, with the same name. Title is required. Limit has a default value of ten, so it's optional. Ampersands separate several parameters. In the terminal, we put the URL in quotes, because of the question mark, and the ampersand. Run it. Without limit, we get ten. With limit equals three, we get three. And with no title at all, Spring answers four hundred.
BookController.javajava
@RestControllerpublic class BookController { @GetMapping("/search") public String search(@RequestParam String title, @RequestParam(defaultValue = "10") int limit) { return "Searching for '" + title + "', up to " + limit + " results"; }}
Output
$ curl "localhost:8080/search?title=dune"
Searching for 'dune', up to 10 results
$ curl "localhost:8080/search?title=dune&limit=3"
Searching for 'dune', up to 3 results
$ curl -i localhost:8080/search | head -1
HTTP/1.1 400
Also uses _curl.sh
curl "localhost:8080/search?title=dune"curl "localhost:8080/search?title=dune&limit=3"curl -i localhost:8080/search | head -1
Required equals false makes a parameter optional. If it's missing, the value is null. So we check for null, and return all books. Run it. Without author, we get all books. With author, we get just theirs.
BookController.javajava
@RestControllerpublic class BookController { @GetMapping("/books") public String books(@RequestParam(required = false) String author) { if (author == null) { return "All books"; } return "Books by " + author; }}
Output
$ curl localhost:8080/books
All books
$ curl "localhost:8080/books?author=Herbert"
Books by Herbert
Query parameters come after a question mark. At Request Param reads them, and can be optional, with a default value, or required equals false. Next, some practice.