Questions Management – Core Question Service – Build API update question 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 a question such as: a Question document object containing the information of a question, a QuestionRepository for manipulation with MongoDB, a QuestionController defining the APIs for Core Question Service starting with “/question” and the connection information to the MongoDB server is configured in the application.properties file. Now, we are going to build this API!

To build API update a question, I will add a method to expose a PUT request “{id}” with the id as the id of the question that we need to update. We also need to define more body data as the new content of the question we will update as follows:

The steps to update a question include:

First, we need to check whether the question that 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 question exists, we will use the information passed in the body data to update the information in the database:

Then returning the new information of the question after updating the database with the HTTP status code of 200 OK.

In case this question 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 updateQuestion() method will now look like this:

Now that we’ve finished building the API to update a question for the Core Question Service, let’s test it out.

Suppose currently in the database I have the following questions:

Questions Management – Core Question Service – Build API update question using Spring WebFlux and Spring Data MongoDB Reactive

then when I request to update the question with id is 5b73593785ddfe03c26a11ea, the result will be:

Questions Management – Core Question Service – Build API update question using Spring WebFlux and Spring Data MongoDB Reactive

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment