zarpat
zarpat

Reputation: 145

PUT method gives NULL JSON

@PutMapping(path = "{studentId}")
public void updateStudent(
        @PathVariable("studentId") Long studentId,
        @RequestParam(required = false) String name,
        @RequestParam(required = false) String email){

    studentService.updateStudent(studentId, name, email);
}

@Transactional
public void updateStudent(Long studentId, String name, String email){

    Student student = studentRepository.findById(studentId)
            .orElseThrow(() -> new IllegalStateException("Student with " +studentId+" does not exist" ));


        student.setName(name);
        student.setEmail(email);
}

}

The problem is when I do PUT method in POSTMAN it gives no error but values in "name" and "email" are NULL. How can I fix it? Here is my POSTMAN request.

https://i.sstatic.net/KHYVW.png

Upvotes: 1

Views: 265

Answers (1)

Beshambher Chaukhwan
Beshambher Chaukhwan

Reputation: 1448

Your api expects optional request params and you are giving request body in postman. The above api will work for /student/1?name=John&[email protected] If you want to use request body to work with this api i.e., form data submit them change the api to use request body which will be (@RequestBody Student studentData) where Student is a class having 2 string variables name & email. You can create a new class StudentRequest having only request attributes for your put/post apis or you can reuse Student class.

@PutMapping(path = "{studentId}")
public void updateStudent(
    @PathVariable("studentId") Long studentId,
    @RequestBody(required = true) Student student){

    studentService.updateStudent(studentId, student);
}


@Transactional
public void updateStudent(Long studentId, Student studentData){
  
     Student student = studentRepository.findById(studentId)
        .orElseThrow(() -> new IllegalStateException("Student with " +studentId+" does not exist" ));
 
     student.setName(studentData.getName());
     student.setEmail(studentData.getEmail());
     studentRepository.save(student);
}

Upvotes: 1

Related Questions