Introduction
This chapter will continue from the previous chapter, where we created a Spring Boot REST API that returns a list of Java Beans as JSON. We will now learn how to use the @PathVariable annotation to create a REST API that can accept and handle path variables.
@PathVariable Annotation Overview
What is @PathVariable?
The @PathVariable annotation in Spring Boot is used to extract values from the URL path and bind them to method parameters in a controller. It helps in mapping dynamic values in the URL to method parameters.
How @PathVariable Works
When a client sends a request to a specific URL, the @PathVariable annotation extracts parts of the URL and assigns them to method parameters. This is useful for accessing and processing specific resources identified by parts of the URL.
Key Features of @PathVariable
- Binding URL Segments to Parameters: It binds segments of the URL directly to method parameters in the controller.
- Dynamic URLs: It allows the creation of dynamic URLs where parts of the URL are variable and can be processed by the controller method.
- Readability and Simplicity: It makes the code more readable and easier to understand by clearly showing which parts of the URL are being used as parameters.
- Default Values: You can specify default values for path variables to handle cases where the variable might not be provided in the URL.
Implementation: Update the Controller Class
In the src/main/java/com/company/restapi/controller directory, open the StudentController class and update it to include new endpoints that accept path variables.
REST API with Single Path Variable
Let’s create a REST API that handles a single path variable in the URL:
@GetMapping("/students/{id}")
public Student getStudentById(@PathVariable Long id) {
return students.stream()
.filter(student -> student.getId().equals(id))
.findFirst()
.orElse(null);
}
Explanation
@GetMapping("/students/{id}"): This annotation maps HTTP GET requests to the/students/{id}URL to thegetStudentByIdmethod.@PathVariable Long id: This annotation binds the value of the{id}path variable to theidparameter in thegetStudentByIdmethod.- Method Logic: The method uses Java streams to filter the list of students and find the one with the matching
id. If a student with the givenidis found, it is returned; otherwise,nullis returned.
REST API with Multiple Path Variables
Let’s create a REST API that handles multiple path variables in the URL:
@GetMapping("/students/{id}/{lastName}")
public Student getStudentByIdAndLastName(@PathVariable Long id, @PathVariable String lastName) {
return students.stream()
.filter(student -> student.getId().equals(id) && student.getLastName().equalsIgnoreCase(lastName))
.findFirst()
.orElse(null);
}
Explanation
@GetMapping("/students/{id}/{lastName}"): This annotation maps HTTP GET requests to the/students/{id}/{lastName}URL to thegetStudentByIdAndLastNamemethod.@PathVariable Long id, @PathVariable String lastName: These annotations bind the values of the{id}and{lastName}path variables to theidandlastNameparameters in thegetStudentByIdAndLastNamemethod.- Method Logic: The method uses Java streams to filter the list of students and find the one with the matching
idandlastName. If a student with the givenidandlastNameis found, it is returned; otherwise,nullis returned.
Full Updated Controller Class
Here is the full updated StudentController class:
package com.company.restapi.controller;
import com.company.restapi.model.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class StudentController {
private List<Student> students = Arrays.asList(
new Student(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com"),
new Student(2L, "Suresh", "Kumar", "suresh.kumar@example.com"),
new Student(3L, "Mahesh", "Yadav", "mahesh.yadav@example.com")
);
@GetMapping("/student")
public Student getStudent() {
return new Student(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com");
}
@GetMapping("/students")
public List<Student> getAllStudents() {
return students;
}
@GetMapping("/students/{id}")
public Student getStudentById(@PathVariable Long id) {
return students.stream()
.filter(student -> student.getId().equals(id))
.findFirst()
.orElse(null);
}
@GetMapping("/students/{id}/{lastName}")
public Student getStudentByIdAndLastName(@PathVariable Long id, @PathVariable String lastName) {
return students.stream()
.filter(student -> student.getId().equals(id) && student.getLastName().equalsIgnoreCase(lastName))
.findFirst()
.orElse(null);
}
}
Running the Application
Step 2: Run Your Spring Boot Application
- Open Application Class:
- Ensure that the main application class (annotated with
@SpringBootApplication) is open.
- Ensure that the main application class (annotated with
- Run the Application:
- In IntelliJ IDEA, right-click the main application class and select “Run ‘SpringbootRestApiApplication'”.
- Alternatively, open a terminal, navigate to the project directory, and run
mvn spring-boot:run.
Step 3: Test Each REST API
- Single Path Variable:
- Request:
GET http://localhost:8080/students/1 - Response:
- Request:

- Multiple Path Variables:
- Request:
GET http://localhost:8080/students/1/Fadatare - Response:
- Request:

Conclusion
In this chapter, we learned how to use the @PathVariable annotation in Spring Boot to create REST APIs that handle single and multiple path variables, as well as path variables with optional request parameters. The @PathVariable annotation in Spring Boot is a powerful and simple way to bind URL segments to method parameters in a controller. It helps in creating dynamic and readable URLs, making it easier to develop and maintain web applications.