Build Delete Student REST API

Introduction

In this chapter, we will build a Delete Student REST API for our Student Management System Project with a MySQL database. We will update the service layer, build the Delete Student REST API, and test it using the Postman client. Each step will be explained in detail.

What We Will Cover in This Chapter

  • Update a Service Layer (interface and implementation class)
  • Build Delete Student REST API
  • Test using Postman client
  • Conclusion

Update a Service Layer

Update the Service Interface

  1. Open StudentService Interface:
    • In the src/main/java/com/example/springbootmysqlcrud/service directory, open the StudentService interface.
    • Add the following method to the StudentService interface:
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);
    void deleteStudent(Long id);
}

Explanation

  • Service Interface: Defines the contract for the service layer. It now includes the deleteStudent method to delete a student by ID.

Update the Service Implementation Class

  1. Open StudentServiceImpl Class:
    • In the src/main/java/com/example/springbootmysqlcrud/service directory, open the StudentServiceImpl class.
    • Add the following method to the StudentServiceImpl class:
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);
    }

    @Override
    public void deleteStudent(Long id) {
        studentRepository.deleteById(id);
    }
}

Explanation

  • deleteStudent Method: Implements the deleteStudent method defined in the StudentService interface to delete a student by ID using the repository.

Build Delete Student REST API

Create or Update the Controller Class

  1. Open StudentController Class:
    • In the src/main/java/com/example/springbootmysqlcrud/controller directory, open the StudentController class.
    • Add the following method to the StudentController class:
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);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
        studentService.deleteStudent(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}

Explanation

  • @DeleteMapping("/{id}"): Handles HTTP DELETE requests to delete a student by ID.
  • @PathVariable: Binds the method parameter to the value of the path variable.
  • ResponseEntity: Wraps the response and sets the HTTP status to 204 No Content for successful deletion.

Test Using Postman Client

Step-by-Step Testing

  1. Open Postman:

    • Launch the Postman client from your installed applications.
  2. Create a New Request:

    • Click on "New" and then select "Request".
  3. Set Request Type and URL:

    • Set the request type to DELETE.
    • Enter the URL: http://localhost:8080/api/students/{id} (replace {id} with the actual student ID).
  4. Send Request:

    • Click the "Send" button.
    • Verify that the response status is 204 No Content if the student is deleted or 404 Not Found if the student does not exist.

Explanation

  • Request Type: DELETE indicates that we are deleting data.
  • URL: Points to the Delete Student REST API endpoint with the student ID as a path variable.
  • Response: Verifies that the student is deleted or that the appropriate error message is shown.

Conclusion

In this chapter, we built a Delete Student REST API for our Student Management System Project with a MySQL database. We updated the service layer, built the Delete Student REST API, and tested it using the Postman client. Each step was explained in detail. This concludes the CRUD operations for the Student Management System Project.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top