Check out the full series of Questions Management tutorial here.
In the previous tutorial, we prepared all the necessary configurations to build API find question by id: 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 the API Question Service will start with “/question” and information about the Composite Question Service is configured in the application.properties file. Now, let’s build this API!
In order to build API find question by id, I would first add a findQuestionById() method in the CompositeQuestionService interface:
1 |
Mono<CompositeQuestion> findQuestionById(String id); |
with the implementation of this method in the CompositeQuestionServiceImpl class is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
@Override public Mono<CompositeQuestion> findQuestionById(String id) { WebClient client = WebClient.builder() .baseUrl(getServiceUrl()) .build(); WebClient.ResponseSpec responseSpec = client.get() .uri("/question/" + id) .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 find question by id of this service with the “/question/{id}” URI.
Next, I will add a method call to the CompositeQuestionService’s findQuestionById() method to expose a GET request “/question/{id}” in ApiQuestionController as follows:
1 2 3 4 5 6 |
@GetMapping("/{id}") public Mono<ResponseEntity<CompositeQuestion>> findQuestionById(@PathVariable(value = "id") String questionId) { return compositeQuestionService.findQuestionById(questionId) .map(category -> ResponseEntity.ok(category)) .defaultIfEmpty(ResponseEntity.notFound().build()); } |
At this point, we have completed the API find question by id for the API Question Service. Let’s try it.