Path Variables & Query Parameters
Two ways to pass values in a URL: path variables identify a thing, query parameters tweak the request.
What you will learn
- Read a path variable with @PathVariable
- Read a query parameter with @RequestParam
- Know when to use each
Two kinds of URL input
URLs often carry values. There are two common spots, and each has its own annotation:
| Type | Looks like | Annotation | Use it to |
|---|---|---|---|
| Path variable | /products/5 | @PathVariable | Identify one specific item |
| Query parameter | /products?max=500 | @RequestParam | Filter, sort or page results |
Path variable: pick one item
Put a placeholder in curly braces in the URL, then read it with @PathVariable:
@GetMapping("/products/{id}")
public String findOne(@PathVariable int id) {
return "You asked for product number " + id;
}Note: Output (visiting /products/5):
You asked for product number 5
The id placeholder in the URL is captured and passed into the method as id. Visiting /products/42 would say “product number 42”.
Query parameter: tweak the request
Query parameters come after a ? as name=value pairs. Read them with @RequestParam:
@GetMapping("/products")
public String filter(@RequestParam(defaultValue = "1000") double max) {
return "Showing products under " + max;
}Note: Output:
Visiting /products -> Showing products under 1000.0 (default used)
Visiting /products?max=500 -> Showing products under 500.0
@RequestParam read the max value from the URL. The defaultValue is used when max is left out, so the endpoint still works.
Tip: Quick rule: if the value names a specific thing (one product, one user), use a path variable. If it adjusts the result (a filter, a limit, a page number), use a query parameter.
Watch out: Without defaultValue (or required = false), a missing @RequestParam causes an error. Add a default for optional filters so the endpoint does not break when the parameter is absent.
Q. Which URL uses a query parameter (not a path variable)?
✍️ Practice
- Add
/books/{id}that returns “Book id: <id>”. - Add
/books?author=Rowlingthat returns “Books by Rowling” using@RequestParam.
🏠 Homework
- Build
/students/{id}(path variable) and/students?course=Java(query param) and test both in the browser.