Building Reactive REST APIs with Spring boot 3.2.0 part III

Timz Owen
5 min readDec 12, 2023

Working with controller and Postman for testing the APIs, a continuation of part II where we built the business Logic.

Building the Controller Layer

This is the final layer where the Restful logic lays. This implements methods created in the Serice Implementation layer.

  1. Create a packagecontroller.
  2. Create a class under controller package- StudentController
  3. Annotation — @RestController & RequestMapping

RequestMapping — provide path for your main Api URL. Example will be “/api/versionOfApi/students”. RestController — Indicates to our IDE that this is a Restful Endpoint (API). @RequiredArgs — Allows us to inject the Student Service class inside the controller.

Now instantiate the service class inside the StudentController. This will allow us to consume the methods from the service class to perform CRUD operations.

    // Inject student service class
private StudentService studentService;

POST Endpoints.

  1. Save single student Record.

This is the Endpoint (API) that save the student record in the database. This is a Mono and not a Flux as its just one record being save. It's annotated with @PostMapping(/url/for/saving). @RequestBody annotation is used to bind the body of a request to a method parameter. This is commonly used in methods that handle HTTP requests as shown.

  @PostMapping("/save")
public Mono<Student> saveStudent(@RequestBody Student student){
return studentService.saveSingleStudent(student);
}

This completes out endpoint and we are ready to save and test in postman. Run your application and your view should look like this.

To enable you to use Endpoints, we have to perform injection in the service implementation class to the repository interface. add @Autowired — This is not recommended, but we shall fix this in the next chapter.

Postman testing.

postman response
  1. POST — Ensure we are post to database and not Fetching. https URL — This is the path where we hit the endpoint.
  2. Raw — specify the type of input you want to send.
  3. JSON — we are sending in Json format [ key — value] pair.
  4. Json values- [KeysString], [values — depends on data type].
  5. Send — actual sending of the data to the database.
  6. Response — shows the data that was sent to the database.
  7. status code — displays code 200 as a success and others codes respectively for the state of the endpoint result.

2. Save Multiple student Record.

This Endpoint saves multiple students in the database as a Flux list of objects. @PostMapping annotation and specify your URL to append to the main Request mapping.

  // Save multiple student records to the database
public Flux<Student> saveAll(Flux<Student> students){
return studentService.saveAllStudents(students);
}

In postman try adding multiple records separated by commas for every Json object in the Json array., make sure to change the URL to “saveAll”

GET Endpoints

Instead of now using the “POST Mapping” we use “GET Mapping” since we are fetching data from the database. @Path Variable get introduced as a parameter where we are referencing “Long” as data type and not Requestbody that's used when referencing an entity of student.

  // Fetch single entity
@GetMapping("/student/{id}")
public Mono<Student> fetchStudent(@PathVariable Long id){
return studentService.findStudentById(id);
}

// Fetch Multiple students from database
@GetMapping("/allStudents")
public Flux<Student> getAllStudents(){
return studentService.findAllStudents();
}

postman test — Get all students.

Get specific student based on id.

UPDATE Mapping

Update Mapping allows us to update existing record in the database. The method update Student is annotated with @PutMapping("/{id}"), indicating that it handles HTTP PUT requests to the "/api/student/{id}" endpoint.

The @PathVariable annotation is used to extract the id from the URL path. The @RequestBody annotation is used to bind the request body (containing the updated data) to the updatedEntity parameter.

 // update mapping
@PutMapping("/student/{id}")
public Mono<Student> updateStudent(@RequestBody Student student, @PathVariable Long id){
return studentService.updateStudent(student,id);
}

you will get a response of 200 — ok. Meaning record has been updated.

DELETE Mapping

To implement a delete operation using a DELETE request in a Spring Boot application with Spring WebFlux, we will use @DeleteMapping annotation in your controller.@DeleteMapping("/{id}"), indicating that it handles HTTP DELETE requests to the "/api/delete/{id}" endpoint. The @PathVariable annotation is used to extract the id from the URL path.

  // delete single record in database
@DeleteMapping("student/{id}")
public String deleteStudent(@PathVariable Long id){
return studentService.deleteById(id);
}

//CAUTION !! this clears the all records
@DeleteMapping("/deleteAll")
public void deleteAllDatabase(){
studentService.deleteAll();
}

delete All records from database.

Finally, we’ve come to the end of the part III……. The Final part IV is cleaning up the code base and handling exceptions.

--

--

Timz Owen

Full stack SRE | DevOps | Automation Engineer. I Love building Tech communities @Africa