Check out the full series of Questions Management tutorial here.
In the previous tutorial, we prepared all the necessary configurations to build API update question such as: an object containing all the information of a question CompositeQuestion including Question, Category, and Option; a CompositeQuestionService interface with CompositeQuestionServiceImpl implementation is responsible for handling the Composite Question Service, an ApiQuestionController that defines the APIs of API Question Service will start with a “/question” and information about the Composite Question Service is configured in the application.properties file. Now, let’s build this API!
To build API update a question, first, I will add an updateQuestion() method in the CompositeQuestionService interface:
1 |
Mono<CompositeQuestion> updateQuestion(String questionId, Question question); |
The implementation of this method calls to the Composite Question Service in the CompositeQuestionServiceImpl class as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override public Mono<CompositeQuestion> updateQuestion(String questionId, Question question) { WebClient client = WebClient.builder() .baseUrl(getServiceUrl()) .build(); WebClient.ResponseSpec responseSpec = client.put() .uri("/question/" + questionId) .body(BodyInserters.fromObject(question)) .retrieve(); return responseSpec.bodyToMono(CompositeQuestion.class); } |
As you can see, here I have used the WebClient object to connect to the Composite Question Service and call the API to update a question with the “/question/{id}” URI.
Next, I will add a method call to the CompositeQuestionService’s updateQuestion() method to expose a PUT request “/question/{id}” in ApiQuestionController as follows:
1 2 3 4 5 6 7 |
@PutMapping("/{id}") public Mono<ResponseEntity<CompositeQuestion>> updateQuestion(@PathVariable(value = "id") String questionId, @RequestBody Question question) { return compositeQuestionService.updateQuestion(questionId, question) .map(compositeQuestion -> ResponseEntity.ok(compositeQuestion)) .defaultIfEmpty(ResponseEntity.notFound().build()); } |
At this point, we have completed the API update question for the API Question Service. Let’s test it.