REST APIsCore· 40 min read

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:

TypeLooks likeAnnotationUse it to
Path variable/products/5@PathVariableIdentify one specific item
Query parameter/products?max=500@RequestParamFilter, sort or page results

Path variable: pick one item

Put a placeholder in curly braces in the URL, then read it with @PathVariable:

A path variable identifies a single product
@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:

A query parameter filters the list (with a default)
@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)?

Answer: A query parameter comes after the ? as name=value, like ?max=500. The others embed a value in the path, which is a path variable.

✍️ Practice

  1. Add /books/{id} that returns “Book id: <id>”.
  2. Add /books?author=Rowling that returns “Books by Rowling” using @RequestParam.

🏠 Homework

  1. Build /students/{id} (path variable) and /students?course=Java (query param) and test both in the browser.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →