Build Get All Students REST API

Introduction

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

What We Will Cover in This Chapter

  • Update a Service Layer (interface and implementation class)
  • Build Get All Students 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();
}

Explanation

  • Service Interface: Defines the contract for the service layer. It now includes the getAllStudents method to retrieve all students.

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();
    }
}

Explanation

  • getAllStudents Method: Implements the getAllStudents method defined in the StudentService interface to retrieve all student entities using the repository.

Build Get All Students 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);
    }
}

Explanation

  • @GetMapping: Handles HTTP GET requests to retrieve all students.
  • ResponseEntity: Wraps the response and sets the HTTP status to 200 OK for successful retrieval.

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 GET.
    • Enter the URL: http://localhost:8080/api/students.
  4. Send Request:

    • Click the "Send" button.
    • Verify that the response status is 200 OK and the response body contains the list of all students.

Explanation

  • Request Type: GET indicates that we are retrieving data.
  • URL: Points to the Get All Students REST API endpoint.
  • Response: Verifies that all student data is returned.

Conclusion

In this chapter, we built a Get All Students REST API for our Student Management System Project with a MySQL database. We updated the service layer, built the Get All Students REST API, and tested it using the Postman client. Each step was explained in detail. In the next chapter, we will build an Update Student REST API.

Leave a Comment

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

Scroll to Top