Request Mapping, Path Variables, and Query Parameters
Request Mapping, Path Variables, and Query Parameters
URLs carry information, and a real API needs to read it in three ways: path segments, query strings, and headers. Spring maps all of them into method parameters with a few annotations, so your controllers stay clean and expressive.
Path variables
A path variable is a named placeholder inside a URL template. To fetch a single product you map /api/products/{id} and read the id with @PathVariable. Spring converts the string segment to your parameter type automatically.
@GetMapping("/{id}")
public Product findById(@PathVariable Long id) {
return service.findById(id);
}
Query parameters
Query parameters arrive after the question mark, like ?size=5&sort=name. Use @RequestParam with a default to keep them optional. This is the idiomatic way to filter lists and control pagination.
@GetMapping
public List<Product> search(@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "name") String sort) {
return service.search(size, sort);
}
Headers and defaults
@RequestHeader reads individual HTTP headers, useful for API keys and client identifiers. Spring also fills in parameters that have default values when the client omits them, which is how you make query parameters effectively optional.
Template matching rules
URL templates must match exactly, and each {...} placeholder needs a matching @PathVariable parameter. Referencing a path variable that does not exist in the template causes an application startup failure, so the compiler cannot save you here - the logs will.
Key Points
@PathVariablereads named segments from the URL template.@RequestParamreads query string values, with defaults for optional inputs.@RequestHeaderexposes HTTP headers to handler methods.- Spring converts string inputs to typed parameters automatically.
- Every
{placeholder}needs a matching@PathVariableargument.