Introduction
In this chapter, we will build an Update Student REST API for our Student Management System Project with a MySQL database. We will update the service layer, build the Update Student REST API, and test it using the Postman client. Each step will be explained in detail. In the next chapter, we will build a Delete Student REST API.
What We Will Cover in This Chapter
- Update a Service Layer (interface and implementation class)
- Build Update Student REST API
- Test using Postman client
- Conclusion
Update a Service Layer
Update the Service Interface
- Open
StudentServiceInterface:- In the
src/main/java/com/example/springbootmysqlcrud/servicedirectory, open theStudentServiceinterface. - Add the following method to the
StudentServiceinterface:
- In the
package com.example.springbootmysqlcrud.service;
import com.example.springbootmysqlcrud.model.Student;
import java.util.List;
import java.util.Optional;
public interface StudentService {
Student saveStudent(Student student);
Optional<Student> getStudentById(Long id);
List<Student> getAllStudents();
Student updateStudent(Long id, Student student);
}
Explanation
- Service Interface: Defines the contract for the service layer. It now includes the
updateStudentmethod to update a student’s details.
Update the Service Implementation Class
- Open
StudentServiceImplClass:- In the
src/main/java/com/example/springbootmysqlcrud/servicedirectory, open theStudentServiceImplclass. - Add the following method to the
StudentServiceImplclass:
- In the
package com.example.springbootmysqlcrud.service;
import com.example.springbootmysqlcrud.model.Student;
import com.example.springbootmysqlcrud.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public Student saveStudent(Student student) {
return studentRepository.save(student);
}
@Override
public Optional<Student> getStudentById(Long id) {
return studentRepository.findById(id);
}
@Override
public List<Student> getAllStudents() {
return studentRepository.findAll();
}
@Override
public Student updateStudent(Long id, Student studentDetails) {
return studentRepository.findById(id)
.map(student -> {
student.setFirstName(studentDetails.getFirstName());
student.setLastName(studentDetails.getLastName());
student.setEmail(studentDetails.getEmail());
return studentRepository.save(student);
})
.orElse(null);
}
}
Explanation
updateStudentMethod: Implements theupdateStudentmethod defined in theStudentServiceinterface to update a student’s details using the repository.
Build Update Student REST API
Create or Update the Controller Class
- Open
StudentControllerClass:- In the
src/main/java/com/example/springbootmysqlcrud/controllerdirectory, open theStudentControllerclass. - Add the following method to the
StudentControllerclass:
- In the
package com.example.springbootmysqlcrud.controller;
import com.example.springbootmysqlcrud.model.Student;
import com.example.springbootmysqlcrud.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/students")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping
public ResponseEntity<Student> saveStudent(@RequestBody Student student) {
Student savedStudent = studentService.saveStudent(student);
return new ResponseEntity<>(savedStudent, HttpStatus.CREATED);
}
@GetMapping("/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
Optional<Student> student = studentService.getStudentById(id);
return student.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@GetMapping
public ResponseEntity<List<Student>> getAllStudents() {
List<Student> students = studentService.getAllStudents();
return new ResponseEntity<>(students, HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student studentDetails) {
Student updatedStudent = studentService.updateStudent(id, studentDetails);
return updatedStudent != null ? new ResponseEntity<>(updatedStudent, HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
Explanation
@PutMapping("/{id}"): Handles HTTP PUT requests to update a student’s details.@PathVariable: Binds the method parameter to the value of the path variable.@RequestBody: Binds the request body to the method parameter.ResponseEntity: Wraps the response and sets the appropriate HTTP status. If the student is updated successfully, it returns200 OK; if the student is not found, it returns404 Not Found.
Test Using Postman Client
Step-by-Step Testing
-
Open Postman:
- Launch the Postman client from your installed applications.
-
Create a New Request:
- Click on "New" and then select "Request".
-
Set Request Type and URL:
- Set the request type to
PUT. - Enter the URL:
http://localhost:8080/api/students/{id}(replace{id}with the actual student ID).
- Set the request type to
-
Set Request Body:
- Click on the "Body" tab.
- Select "raw" and "JSON".
- Enter the following JSON data:
{
"firstName": "UpdatedFirstName",
"lastName": "UpdatedLastName",
"email": "updated.email@example.com"
}
- Send Request:
- Click the "Send" button.
- Verify that the response status is
200 OKif the student is updated or404 Not Foundif the student does not exist.
Explanation
- Request Type:
PUTindicates that we are updating data. - URL: Points to the Update Student REST API endpoint with the student ID as a path variable.
- Request Body: Contains the updated student details in JSON format.
- Response: Verifies that the student’s details are updated or that the appropriate error message is shown.
Conclusion
In this chapter, we built an Update Student REST API for our Student Management System Project with a MySQL database. We updated the service layer, built the Update Student REST API, and tested it using the Postman client. Each step was explained in detail. In the next chapter, we will build a Delete Student REST API.