To understand post 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.
Name | Roll | Age | ClassName |
---|---|---|---|
John | 1 | 8 | 5 |
Paul | 2 | 7 | 5 |
Andrew | 3 | 8 | 5 |
Now, the school Inspector came up with a new requirement.
He said that there is a new student named Kevin, whose age is 9 and he should be placed in class 5.
Name | Roll | Age | ClassName |
---|---|---|---|
Kevin | 4 | 9 | 5 |
Let's just assume, the roll number of Kevin be 4.
So, you being the Principal, all you need to do is, add the new student named Kevin to the existing List.
And how would you do that?
In the earlier tutorials we have seen that if we had requested student details, we got the response in JSON format.
Let us take the JSON response from the above image and format it properly :
[ {"name":"John","roll":1,"age":8,"className":5}, {"name":"Paul","roll":2,"age":7,"className":5}, {"name":"Andrew","roll":3,"age":8,"className":5} ]
Now, in this case, we have to add the details of the student Kevin to the above JSON.
{"name":"Kevin","roll":4,"age":9,"className":5}
So, how to get it done?
Let us understand with the below steps :
@RestController public class HelloWorldController { @Autowired StudentService studentService; @RequestMapping("/students") public ListnumberOfStudents() { return studentService.studentDetails(); } @RequestMapping(method = RequestMethod.POST, value = "/students") public void addStudent(@RequestBody Student student) { studentService.addNewStudent(student); } }
@RequestMapping(method = RequestMethod.POST, value = "/students") public void addStudent(@RequestBody Student student) { studentService.addNewStudent(student); }
@RequestMapping(method = RequestMethod.POST, value = "/students")
{"name":"Kevin","roll":4,"age":9,"className":5}
localhost:8080/students
{"name": "Kevin", "roll": 4, "age": 8, "className": 5}
public void addStudent(@RequestBody Student student)
{"name": "Kevin", "roll": 4, "age": 8, "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) )); public List studentDetails() { return studentList; } public void addNewStudent(Student student) { studentList.add(student); } } The addNewStudent(...) method is called. public void addNewStudent(Student student) { studentList.add(student); }
ListstudentList = new ArrayList<>(Arrays.asList( new Student("John", 1, 8, 5), new Student("Paul", 2, 7, 5), new Student("Andrew", 3, 8, 5) ));