Check out the full series of Questions Management tutorial here.
In the previous tutorial, we prepared all the necessary configurations to be able to build API delete a question such as: a Question document object containing the information of a question, a QuestionRepository to manipulate MongoDB, a QuestionController defines APIs for Core Question Service will start with “/question” and the connection information to the MongoDB server is configured in the application.properties file. Now, let’s build this API!
To build API delete a question, I will add a method in the QuestionController class to expose a DELETE request “{id}” with the id of the question we want to delete:
1 2 3 4 |
@DeleteMapping("/{id}") public Mono<ResponseEntity<Void>> deleteQuestion(@PathVariable(value = "id") String questionId) { } |
Steps to remove a question include:
First, we need to check whether the question we want to delete does exist or not based on the id that the user casts.
Spring Data MongoDB Reactive has provided us with a way to search by id so we just need to call it.
1 |
questionRepository.findById(questionId) |
In case this question exists, we will delete it and return the HTTP status code to 200 OK.
1 2 3 |
questionRepository.findById(questionId) .flatMap(existingQuestion -> questionRepository.delete(existingQuestion) .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))) |
If it does not exist, return the HTTP status code of 404 Not Found.
1 2 3 4 |
return questionRepository.findById(questionId) .flatMap(existingQuestion -> questionRepository.delete(existingQuestion) .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))) .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND)); |
The entire contents of the deleteQuestion() method will now look like this:
1 2 3 4 5 6 7 |
@DeleteMapping("/{id}") public Mono<ResponseEntity<Void>> deleteQuestion(@PathVariable(value = "id") String questionId) { return questionRepository.findById(questionId) .flatMap(existingQuestion -> questionRepository.delete(existingQuestion) .then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))) .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } |
At this point, we have finished building API to delete a question for Core Question Service, let’s test it out!
Suppose I currently have the following questions:
if I request to delete question with id is 5ad5d9d651bd7a0aefa87fb3, the result will be: