0
0
SpringbootConceptBeginner · 3 min read

@PathVariable in Spring Boot: What It Is and How to Use It

@PathVariable in Spring Boot is an annotation used to extract values from the URL path and bind them to method parameters in a controller. It allows your application to capture dynamic parts of the URL and use them in your code.
⚙️

How It Works

Imagine you have a website where users can view profiles by their user ID, like /users/123. The @PathVariable annotation helps your Spring Boot app grab that 123 from the URL and pass it to your code as a variable.

It works by matching parts of the URL path defined in your controller's route pattern with method parameters. When a request comes in, Spring Boot looks at the URL, finds the matching pattern, and fills in the method parameters with the values from the URL.

This is like filling in blanks in a form: the URL is the form, and @PathVariable tells Spring Boot which blanks to fill with which values.

💻

Example

This example shows a simple Spring Boot controller that uses @PathVariable to get a user ID from the URL and return a message with that ID.

java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public String getUserById(@PathVariable String id) {
        return "User ID is: " + id;
    }
}
Output
User ID is: 123
🎯

When to Use

Use @PathVariable when you want to capture dynamic values from the URL path itself, such as IDs, names, or other identifiers. This is common in REST APIs where resources are accessed by unique keys.

For example, if you have a product catalog, you might use @PathVariable to get the product ID from URLs like /products/456. This makes your URLs clean and easy to understand, and your code can directly work with the values from the URL.

Key Points

  • @PathVariable binds URL path segments to method parameters.
  • It helps handle dynamic URLs in RESTful web services.
  • Parameter names in the method should match the placeholders in the URL pattern.
  • You can specify the variable name explicitly in @PathVariable("name").
  • It makes URLs more readable and meaningful.

Key Takeaways

@PathVariable extracts dynamic values from URL paths in Spring Boot controllers.
It is essential for building REST APIs with clean, readable URLs.
Method parameter names should match the path variable names or be explicitly specified.
Use it to capture IDs or other identifiers directly from the URL.
It improves code clarity by linking URL parts to method inputs.