Labs ICT
โญ Pro Login

Path Variables

Capturing values from the URL.

The @PathVariable Annotation

Path variables let you extract values directly from the URL path. Instead of passing IDs as query parameters, you embed them in the URL itself โ€” like /users/42 instead of /users?id=42.

This is the RESTful way to identify resources. The @PathVariable annotation binds a URL template variable to a method parameter automatically.

URL Path Extraction

Declare a path variable in your mapping using curly braces, then reference it in your method parameter. Spring does the heavy lifting of parsing the URL and converting the value to the correct type.

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    return userService.findById(id);
}

When a request hits /users/42, Spring extracts 42 and assigns it to the id parameter as a Long.

Multiple Path Variables

You can have multiple path variables in a single URL. Each one maps to a corresponding method parameter by name.

@GetMapping("/stores/{storeId}/products/{productId}")
public Product getProduct(
        @PathVariable Long storeId,
        @PathVariable Long productId) {
    return productService.findByStoreAndId(storeId, productId);
}

The names in curly braces must match the parameter names. If they don't, use the name attribute: @PathVariable(name = "storeId") Long store.

Path Variable Constraints

You can add constraints to path variables to narrow down what matches. For example, {id:\\d+} only matches numeric strings. This prevents your controller from catching URLs it wasn't designed to handle.

Constraints also help with routing precision. If two controllers could match the same pattern, a more specific constraint ensures requests go to the right place. It's like having a bouncer at the door checking IDs before letting people in.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What does @PathVariable do?