Questions Management – Core Option Service – Build API update option using Spring WebFlux and Spring Data MongoDB Reactive

Check out the full series of Questions Management tutorial here.

In the previous tutorial, we prepared all the necessary configurations to build API update option such as an Option document object containing the information of an option, an OptionRepository for manipulation with MongoDB, an OptionController defines APIs for Core Option Service starting with “/option” and the connection information to the MongoDB server is configured in the application.properties file. Now, let’s build this API!

To build API update option, I would add a method in the OptionController class to expose a PUT request “/option/{id}” with id as id of the option that we need to update.

The steps to update an option include:

First, we need to check that the option we need to update does exist or not based on the id that the user is passing on.

Spring Data MongoDB Reactive has provided us with a way to search by id so we just need to call it.

In case this option exists, we will use the information passed in the body data to update the information in the database:

Then returning to the user new information of this option after having updated the database with the HTTP status code of 200 OK.

In case this option does not exist in the database, we will return the result of the HTTP status code is 404 Not Found.

The entire contents of the updateOption() method will now look like this:

At this point we have finished building the API to update an option for the Core Option Service.

Currently I have the following options:

Questions Management – Core Option Service – Build API update option using Spring WebFlux and Spring Data MongoDB Reactive

the when I request to update option with id is 5b871766f62c5604f6a6a8fb, the result will be:

Questions Management – Core Option Service – Build API update option using Spring WebFlux and Spring Data MongoDB Reactive

Add Comment