Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this quick tutorial, we’ll explore Spring’s @PathVariable annotation.

Simply put, the @PathVariable annotation can be used to handle template variables in the request URI mapping, and set them as method parameters.

Let’s see how to use @PathVariable and its various attributes.

Further reading:

Spring @RequestParam vs @PathVariable Annotations

Understand the differences between Spring's @RequestParam and @PathVariable annotations.

Validating RequestParams and PathVariables in Spring

Learn how to validate request parameters and path variables with Spring MVC

Spring MVC @PathVariable with a dot (.) gets truncated

Learn how to handle path variables that contain a dot in Spring MVC request mappings.

2. A Simple Mapping

A simple use case of the @PathVariable annotation would be an endpoint that identifies an entity with a primary key:

@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesById(@PathVariable String id) {
    return "ID: " + id;
}

In this example, we use the @PathVariable annotation to extract the templated part of the URI, represented by the variable {id}.

A simple GET request to /api/employees/{id} will invoke getEmployeesById with the extracted id value:

http://localhost:8080/api/employees/111 
---- 
ID: 111

Now let’s further explore this annotation, and have a look at its attributes.

3. Specifying the Path Variable Name

In the previous example, we skipped defining the name of the template path variable since the names for the method parameter and the path variable were the same.

However, if the path variable name is different, we can specify it in the argument of the @PathVariable annotation:

@GetMapping("/api/employeeswithvariable/{id}")
@ResponseBody
public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) {
    return "ID: " + employeeId;
}
http://localhost:8080/api/employeeswithvariable/1 
---- 
ID: 1

We can also define the path variable name as @PathVariable(value=”id”) instead of PathVariable(“id”) for clarity.

4. Multiple Path Variables in a Single Request

Depending on the use case, we can have more than one path variable in our request URI for a controller method, which also has multiple method parameters:

@GetMapping("/api/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) {
    return "ID: " + id + ", name: " + name;
}
http://localhost:8080/api/employees/1/bar 
---- 
ID: 1, name: bar

We can also handle more than one @PathVariable parameter using a method parameter of type java.util.Map<String, String>:

@GetMapping("/api/employeeswithmapvariable/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndNameWithMapVariable(@PathVariable Map<String, String> pathVarsMap) {
    String id = pathVarsMap.get("id");
    String name = pathVarsMap.get("name");
    if (id != null && name != null) {
        return "ID: " + id + ", name: " + name;
    } else {
        return "Missing Parameters";
    }
}
http://localhost:8080/api/employees/1/bar 
---- 
ID: 1, name: bar

There is, however, a small catch while handling multiple @PathVariable parameters when the path variable string contains a dot(.) character. We’ve discussed those corner cases in detail here.

5. Optional Path Variables

In Spring, method parameters annotated with @PathVariable are required by default:

@GetMapping(value = { "/api/employeeswithrequired", "/api/employeeswithrequired/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequired(@PathVariable String id) {
    return "ID: " + id;
}

Given how it looks, the above controller should handle both /api/employeeswithrequired and /api/employeeswithrequired/1 request paths. However, since method parameters annotated by @PathVariables are mandatory by default, it doesn’t handle the requests sent to the /api/employeeswithrequired path:

http://localhost:8080/api/employeeswithrequired 
---- 
{"timestamp":"2020-07-08T02:20:07.349+00:00","status":404,"error":"Not Found","message":"","path":"/api/employeeswithrequired"} 

http://localhost:8080/api/employeeswithrequired/1 
---- 
ID: 111

We can handle this in two different ways.

5.1. Setting @PathVariable as Not Required

We can set the required property of @PathVariable to false to make it optional. Thus, modifying our previous example, we can now handle the URI versions with and without the path variable:

@GetMapping(value = { "/api/employeeswithrequiredfalse", "/api/employeeswithrequiredfalse/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) {
    if (id != null) {
        return "ID: " + id;
    } else {
        return "ID missing";
    }
}
http://localhost:8080/api/employeeswithrequiredfalse 
---- 
ID missing

5.2. Using java.util.Optional

Since the introduction of Spring 4.1, we can also use java.util.Optional<T> (available in Java 8+) to handle a non-mandatory path variable:

@GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" })
@ResponseBody
public String getEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
    if (id.isPresent()) {
        return "ID: " + id.get();
    } else {
        return "ID missing";
    }
}

Now if we don’t specify the path variable id in the request, we get the default response:

http://localhost:8080/api/employeeswithoptional 
----
ID missing 

5.3. Using a Method Parameter of Type Map<String, String>

As shown earlier, we can use a single method parameter of type java.util.Map to handle all the path variables in the request URI. We can also use this strategy to handle the optional path variables case:

@GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" })
@ResponseBody
public String getEmployeesByIdWithMap(@PathVariable Map<String, String> pathVarsMap) {
    String id = pathVarsMap.get("id");
    if (id != null) {
        return "ID: " + id;
    } else {
        return "ID missing";
    }
}

6. Default Value for @PathVariable

Out of the box, there isn’t a provision to define a default value for method parameters annotated with @PathVariable. However, we can use the same strategies discussed above to satisfy the default value case for @PathVariable, we just need to check for null on the path variable.

For instance, using java.util.Optional<String, String>, we can identify if the path variable is null or not. If it is null, then we can just respond to the request with a default value:

@GetMapping(value = { "/api/defaultemployeeswithoptional", "/api/defaultemployeeswithoptional/{id}" })
@ResponseBody
public String getDefaultEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
    if (id.isPresent()) {
        return "ID: " + id.get();
    } else {
        return "ID: Default Employee";
    }
}

7. Conclusion

In this article, we discussed how to use Spring’s @PathVariable annotation. We also identified the various ways to effectively use the @PathVariable annotation to suit different use cases, such as optional parameters and dealing with default values.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW