Path Variables and Query Parameters

@PathVariable

A path variable is part of the URL path that identifies a resource: /api/products/7. Put {name} in the mapping and a parameter annotated with @PathVariable. Spring converts the text to the parameter type (Long, int, UUID...).

@GetMapping("/{id}")
public Product get(@PathVariable Long id) { ... }

// Several variables, and a different parameter name
@GetMapping("/categories/{category}/products/{productId}")
public Product inCategory(@PathVariable String category,
                          @PathVariable("productId") Long id) { ... }

Example

If the text cannot be converted (here abc is not a number) Spring answers 400 before your method runs:

curl -i localhost:8080/api/products/abc

Example output

HTTP/1.1 400 Bad Request
Content-Type: application/json

{"timestamp":"2026-10-12T10:15:30.120+00:00","status":400,"error":"Bad Request","path":"/api/products/abc"}

@RequestParam

A query parameter comes after ? and filters, sorts or pages a list: /api/products?category=Electronics&maxPrice=1000. Parameters are required by default; use required = false or defaultValue for optional ones.

@GetMapping
public List<Product> search(
        @RequestParam(required = false) String category,
        @RequestParam(required = false) BigDecimal maxPrice,
        @RequestParam(defaultValue = "name") String sort,
        @RequestParam(defaultValue = "0") int page) {
    return service.search(category, maxPrice, sort, page);
}

Example

curl "localhost:8080/api/products?category=Electronics&maxPrice=1000"

Example output

[{"id":1,"name":"Wireless Mouse","description":"2.4 GHz, silent clicks","price":799.00,"stock":120,"category":"Electronics"}]

Path Variable or Query Parameter?

UseWhenExample
Path variableIdentifies one resource/api/products/7, /api/orders/1001/items
Query parameterFilters, sorts, pages or searches a collection/api/products?category=Books&sort=price

Tip: The Spring Boot Maven/Gradle plugin compiles with -parameters, so @PathVariable Long id knows its name is id. If you build outside the Boot parent POM, add the flag or write @PathVariable("id").

Exercise: Write a method for GET /api/products/top?limit=5 where limit is optional and defaults to 10.

Show answer
@GetMapping("/top")
public List<Product> top(@RequestParam(defaultValue = "10") int limit) {
    return service.topSelling(limit);
}