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

Query Parameters

?name=value.

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

Another way to send values is the query string. It comes after a question mark at the end of the URL, like question mark title equals dune.

  • After the ?
  • name=value
  • Joined with &

Path variable or query parameter?

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.

Path variable

  • /books/3Which thing?Required

Query parameter

  • /books?author=tolkienFilter, sort, pageOften optional

@RequestParam

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
@RestController
public 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

Optional parameters

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
@RestController
public 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
Also uses _curl.sh
curl localhost:8080/books
curl "localhost:8080/books?author=Herbert"

Summary

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.

Key takeaways
  • ?title=dune&limit=3
  • @RequestParam
  • defaultValue / required
Next up: Practice: A Greeting API — your turn