DEV Community

Jane for Mastering Backend

Posted on • Originally published at blog.masteringbackend.com

Mastering @PathVariable in Spring Boot


Mastering @PathVariable in Spring Boot

Learn how to use @PathVariable in Spring Boot to build clean and RESTful APIs with practical examples from real-world scenarios like users, products, and orders.

What is @PathVariable

@PathVariable in Spring Boot is an annotation used to bind values from the URL directly to method parameters in a controller. It is mainly used in REST APIs where resources are identified using hierarchical URLs. For example, in /users/101, the value 101 represents a specific user and is captured using @PathVariable.

@PathVariable is used in Spring Boot to extract values from the URL path and bind them to method parameters to identify specific resources in REST APIs.

It differs from query parameters because it is part of the URL path, making APIs more readable and meaningful. In real-world systems like e-commerce or CRM, it is commonly used to fetch specific records, such as a user, product, or order, by ID. It also supports multiple values and even dynamic mapping using a Map structure when needed.

In Spring Boot, @PathVariable is used to extract dynamic values from the URL. It helps in designing RESTful APIs where resources are clearly identified using URL paths instead of query parameters.

Let’s start with a simple example:

@GetMapping("/users/{userId}")
public String getUser(@PathVariable Long userId) {
    return "User ID: " + userId;
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

When a request like /users/101 is made, Spring automatically maps 101 to the userId variable.

Now consider a real-world scenario in an e-commerce system where a user wants to view a specific product:

@GetMapping("/users/{userId}/products/{productId}")
public String getUserProduct(@PathVariable Long userId,
                             @PathVariable Long productId) {
    return "User: " + userId + ", Product: " + productId;
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

This makes the API intuitive and readable.

You can also customize variable names:

@GetMapping("/users/{userId}/orders/{orderId}")
public String getOrder(@PathVariable(name = "userId") Long id,
                       @PathVariable Long orderId) {
    return "User: " + id + ", Order: " + orderId;
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

For dynamic cases, you can use a Map:

@GetMapping("/users/{userId}/address/{addressId}")
public String getAddress(@PathVariable Map<String, String> pathVars) {
    return "User: " + pathVars.get("userId") +
           ", Address: " + pathVars.get("addressId");
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

This is useful when handling flexible URLs.

In real-world applications like CRM or booking systems, @PathVariable is used to fetch user details, order history, or product information based on unique identifiers.

Best practices include using meaningful variable names, avoiding too many path variables in one endpoint, and validating inputs properly. Also, prefer strongly typed variables over Map when possible.

Using @PathVariable correctly improves API clarity, maintainability, and aligns with REST standards followed in production-grade applications.

Have a great one!!!

Author: Ayush Shrivastava


Thank you for being a part of the community

Before you go:

Whenever you’re ready

There are 4 ways we can help you become a great backend engineer:

  • The MB Platform: Join thousands of backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learning and set schedules, and solve backend engineering tasks, exercises, and challenges.
  • The MB Academy: The “MB Academy” is a 6-month intensive Advanced Backend Engineering Boot Camp to produce great backend engineers.
  • Join Backend Weekly: If you like posts like this, you will absolutely enjoy our exclusive weekly newsletter, sharing exclusive backend engineering resources to help you become a great Backend Engineer.
  • Get Backend Jobs: Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board.

Top comments (0)