Home > front end >  Can I post multiple objects to a REST service but only one as @RequestParams and how to call it from
Can I post multiple objects to a REST service but only one as @RequestParams and how to call it from

Time:01-25

So I have a method that looks like this:

@PostMapping("/endpoint")
void  myMethod(Student student, @RequestBody Teacher teacher)
{
    //need to be able to access student.getName();
     //Need to be able to access teacher.getName();
}

This is given, I can not change this. Question how do I call this method from PostMan.

I use Post request : localhost:8080/endpoint and in the body, I select : raw and JSON but I can not figure what I am doing from here, as when I put json I ont see values in the student object it is null, not sure how to create a correct json,

class Student {
String id;
String nameStudent;
}
Class Teacher{
String id, 
String nameTeacher;
}

CodePudding user response:

An HTTP POST can only have ONE body. As commenters have indicated, but I will spell out to provide clarity, you have the following two options:

Create a class which combines Student & Teacher and use that as the request body:

class Payload {
    Student student;
    Teacher teacher;
}

@PostMapping("/endpoint")
void  myMethod(@RequestBody Payload payload) {
    Student student = payload.student;
    Teacher teacher = payload.teacher;

JSON payload for Postman:

{
    "student": {
        "id": "abc",
        "name": "A Student name"
    },
    "teacher": {
        "id": "def",
        "name": "A Teacher name"
    }
}

The other option is to pass though the Student attributes as query parameters:

@PostMapping("/endpoint")
void  myMethod(@RequestParam studentId, @RequestParam studentName, @RequestBody Teacher teacher) {
    Student student = new Student(studentId, studentName);

And the studentId & studentName must be submitted as parameters from Postman.

  • Related