Almost every real endpoint needs some input from the caller, and the URL itself is one of the most common places to carry it. Spring Boot gives two complementary tools for this: path variables, which are part of the URL structure, and query parameters, which are optional extras appended after a question mark. Knowing which one fits a given situation makes an API much easier to use correctly.

Path variables

A path variable identifies a specific resource and is embedded directly in the URL path, such as the 5 in /users/5. It is captured with @PathVariable:

@GetMapping("/users/{id}")
public String find(@PathVariable Long id) {
  return "You asked for user " + id;
}

Spring automatically converts the text from the URL into the declared type, so a request to /users/5 arrives as the Long value 5 rather than the text "5". If the value cannot be converted, for example letters where a number is expected, Spring responds with a 400 Bad Request automatically, without any extra code.

Multiple path variables

A path can carry more than one variable when a resource is nested inside another, such as a comment belonging to a specific post:

@GetMapping("/posts/{postId}/comments/{commentId}")
public String getComment(@PathVariable Long postId,
                         @PathVariable Long commentId) {
  return "Post " + postId + ", comment " + commentId;
}

Query parameters

A query parameter comes after a question mark in the URL, like /search?term=java, and is meant for optional extras rather than identifying a resource, such as filters, sorting or pagination. It is captured with @RequestParam:

@GetMapping("/search")
public String search(@RequestParam String term) {
  return "Searching for " + term;
}

Making a parameter optional

By default, @RequestParam requires the parameter to be present, and a missing one causes an error. A default value avoids this and makes the parameter genuinely optional:

@GetMapping("/products")
public String list(@RequestParam(defaultValue = "0") int page,
                   @RequestParam(required = false) String category) {
  return "page=" + page + ", category=" + category;
}

Choosing the right one

  • Use a path variable when the value identifies exactly which resource is being requested, like a user id or a product id.
  • Use a query parameter for options that shape the response without identifying a different resource, such as filtering, sorting, searching or paging.

Following this distinction consistently makes an API predictable: anyone reading a URL can tell at a glance whether a value names a specific thing or simply adjusts how the results are returned, which matters more as an API grows past a handful of endpoints.