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 update option such as: an object containing all the information of an Option; a CoreOptionService interface with the implementation CoreOptionServiceImpl is responsible for handling the Core Option Service; an OptionController defines the APIs of the API Option Service that will start with “/option” and information about the Core Option Service is configured in the application.properties file. Now, let’s build this API!
To build API update option, I will first add a new updateOption() method in the CoreOptionService interface:
1 |
Mono<Option> updateOption(String optionId, Option option); |
The implementation of this method calls the Core Option Service in the CoreOptionServiceImpl class as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
@Override public Mono<Option> updateOption(String optionId, Option option) { WebClient webClient = WebClient.builder() .baseUrl(getServiceUrl()) .build(); return webClient.put() .uri("/option/" + optionId) .body(BodyInserters.fromObject(option)) .retrieve() .bodyToMono(Option.class); } |
As you can see, here I have used the WebClient object to connect to the Core Option Service and call the API to update the option of this service with the “/option/{id}” URI.
Next, I will add a method call to the CoreOptionService updateOption() method to expose a PUT request “/option/{id}” in OptionController as follows:
1 2 3 4 5 6 7 |
@PutMapping("/{id}") public Mono<ResponseEntity<Option>> updateCategory(@PathVariable(value = "id") String optionId, @RequestBody Option option) { return coreOptionService.updateOption(optionId, option) .map(o -> ResponseEntity.ok(o)) .defaultIfEmpty(ResponseEntity.notFound().build()); } |
At this point, we have completed the API update option for the API Option Service. Let’s try it.