To understand PUT method in rest API, let us take the below example.
So far in the previous tutorials we have seen that the school Inspector visited the school and you being the Principal of the school were responsible to provide him all the names of the students of class 5.
He also asked you to add a new student named Kevin, which we have done in the previous tutorial.
Name | Roll | Age | ClassName |
---|---|---|---|
John | 1 | 8 | 5 |
Paul | 2 | 7 | 5 |
Andrew | 3 | 8 | 5 |
Kevin | 4 | 9 | 5 |
Now, the school Inspector came up with a new requirement.
He asked you to Update the name of the student Kevin to Kevin Killian and also update his age from 9 to 10.
So, you being the Principal, all you need to do is, use the PUT method to update the name and age of Kevin.
And how would you do that?
Let us understand with the below steps :
@RestController public class HelloWorldController { @Autowired StudentService studentService; @RequestMapping("/students") public ListnumberOfStudents() { return studentService.studentDetails(); } @RequestMapping(method = RequestMethod.PUT, value = "/students/{name}") public void updateStudent(@RequestBody Student student, @PathVariable String name) { studentService.updateExistingStudent(name, student); } }
@RequestMapping(method = RequestMethod.PUT, value = "/students/{name}") public void updateStudent(@RequestBody Student student, @PathVariable String name) { studentService.updateExistingStudent(name, student); }
@RequestMapping(method = RequestMethod.PUT, value = "/students/{name}")
{"name":"Kevin Killian","roll":4,"age":10,"className":5}
{"name":"Kevin Killian","roll":4,"age":10,"className":5}
localhost:8080/students/Kevin
{"name":"Kevin Killian","roll":4,"age":10,"className":5}
public void updateStudent(@RequestBody Student student, @PathVariable String name)
{"name":"Kevin Killian","roll":4,"age":10,"className":5}
@Service public class StudentService { ListstudentList = new ArrayList<>(Arrays.asList( new Student("John", 1, 8, 5), new Student("Paul", 2, 7, 5), new Student("Andrew", 3, 8, 5), new Student("Kevin", 4, 9, 5) )); public List studentDetails() { return studentList; } public void updateExistingStudent(String name, Student student) { for (Student studentTemp : studentList) { if (studentTemp.getName().equals(name)) { int i = studentList.indexOf(studentTemp); studentList.set(i, student); } } } } The updateExistingStudent(...) method is called. public void updateExistingStudent(String name, Student student) { for (Student studentTemp : studentList) { if (studentTemp.getName().equals(name)) { int i = studentList.indexOf(studentTemp); studentList.set(i, student); } } }
ListstudentList = new ArrayList<>(Arrays.asList( new Student("John", 1, 8, 5), new Student("Paul", 2, 7, 5), new Student("Andrew", 3, 8, 5), new Student("Kevin", 4, 9, 5) ));