Previously, we used @RestController to handle the REST request to get the list of students(http://localhost:8080/api/students).
Now, assume we have a list of students, and the client only wants the first one. So we need to retrieve a single student by id: api/getStudentById/{studentId}
Behind the scenes
- We’ll make a request across for /api/students/{studentId}
- We’ll have Spring REST along with Jackson and they’ll make a call to the REST service
- In our code, we’ll actually return that given student
- Jackson will actually convert that student object or that student POJO to JSON and then send it back across to the REST client
Development Process
Add request mapping to Spring REST Service
- Bind path variable to method parameter using @PathVariable
1
2
3
4
5
6
7
8
9
10
11"/getStudentById/{studentId}") (
<!-- the parameter should be the same as the content in the bracket(studentId) -->
public Student getStudentById(@PathVariable int studentId) {
List<Student> theStudents = new ArrayList<>();
theStudents.add(new Student("Poornima","Patel"));
theStudents.add(new Student("Mario","Rossi"));
theStudents.add(new Student("Mary","Smith"));
return theStudents.get(studentId);
}
- Bind path variable to method parameter using @PathVariable
Test
Postman:
GET:http://localhost:8080/SpringRESTDemo_war_exploded/api/getStudentById/1