Using @PathVariable in Spring Boot Retrieve Data from Dynamic URLs
When developing REST APIs, it’s common to retrieve dynamic data directly from the URL. Spring Boot offers the @PathVariable annotation to…
Using @PathVariable in Spring Boot Retrieve Data from Dynamic URLs

When developing REST APIs, it’s common to retrieve dynamic data directly from the URL. Spring Boot offers the @PathVariable annotation to make this process straightforward and efficient.
In this blog post, I’ll walk you through how to use @PathVariable by building a real example: retrieving an employee by ID.
Use Case: Get Employee by ID
Let’s say er already have a list of employees. Now we want to build an endpoint that returns a specific employee by their ID.
Here is the controller method we’ll use:
@GetMapping(path = "/employee-list/{id}")
public Employee getEmployeeById(@PathVariable(name = "id", required = true) String id) {
return employeeService.getEmployeeById(id);
}
Explanation
- /employee-list/{id} : This endpoint accepts a dynamic id value in the URL.
- @PathVariable( name = “id”, required = true) : This annotation tells Spring to extract id from the URL and pass it into the method.
Service And Repository Layers
In the EmployeeService, we delegate the logic to the repository:
public Employee getEmployeeById(String id) {
return employeeRepository.getEmployeeById(id);
}
And in the repository, we search the list of employees for a matching ID:
public Employee getEmployeeById( String id ) {
Employee findEmployee = null;
for( Employee employee: employeeList) {
if( id.equels(employee.getId())) {
return employee;
break;
}
}
return findEmployee;
}
Testing the API with Postman
You can retrieve the employee with ID 2 by sending this request:
GET http://localhost:8080/rest/api/employee-list/2
Response:
{
"id": "2",
"firstName": "Ahmet",
"lastName": "Alan"
}
✅Why Use @PathVariable?
- Provides clean and RESTful URL structure
- Avoids unnecessary query parameters
- Simplifies endpoint definations
🎯 Conclusion
Using @PathVariable in Spring Boot is one of the easiest and most powerful ways to build flexible REST APIs. With just a few lines of code, you can extract dynamic values from the URL and return personalized results.
메타데이터
- post_id
- 87f71f2d6469
- slug
- using-pathvariable-in-spring-boot-retrieve-data-from-dynamic-urls-87f71f2d6469
- url
- https://medium.com/@gorursevim/using-pathvariable-in-spring-boot-retrieve-data-from-dynamic-urls-87f71f2d6469
- canonical_url
- https://medium.com/@gorursevim/using-pathvariable-in-spring-boot-retrieve-data-from-dynamic-urls-87f71f2d6469
- author_url
- https://medium.com/@gorursevim
- status
- ok
- fetched_at
- 2026-08-03 07:38:58