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 add new question: an object containing all the information of a question CompositeQuestion, including a Question, a Category, and an Option; a CompositeQuestionService interface with CompositeQuestionServiceImpl implementation is responsible for handling the Composite Question Service, an ApiQuestionController that defines the APIs for 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 add new question, first I will add a new createNewQuestion() method in the CompositeQuestionService interface:
1 |
Mono<CompositeQuestion> createNewQuestion(Question question); |
The implementation of this method calls 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> createNewQuestion(Question question) { WebClient client = WebClient.builder() .baseUrl(getServiceUrl()) .build(); WebClient.ResponseSpec responseSpec = client.post() .uri("/question/add") .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 add a new question of this service with the “/question/add” URI.
Next, I’m going to add a method call to the CompositeQuestionService’s createNewQuestion() method to expose a POST request “/question/add” in ApiQuestionController like this:
1 2 3 4 5 6 |
@PostMapping("/add") public Mono<ResponseEntity<CompositeQuestion>> createNewQuestion(@RequestBody Question question) { return compositeQuestionService.createNewQuestion(question) .map(compositeQuestion -> ResponseEntity.ok(compositeQuestion)) .defaultIfEmpty(ResponseEntity.notFound().build()); } |
At this point, we have completed the API to add new question for API Question Service. Let’s try it.