Check out the full series of Questions Management tutorial here.
In the previous tutorial, we prepared all the necessary configurations for building API find options by id of question: a Option document object containing the information of an option, an OptionRepository to manipulate MongoDB, an OptionController that defines the Core Option Service APIs will start with “/option” 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 find options by id of question, we will first define a method in the OptionRepository to help us find information about the options based on the id of the question:
1 |
Flux<Option> findByQuestionId(String questionId); |
Since we are using Spring Data MongoDB Reactive, we do not need to implement this method.
Next, I’m going to add a method to expose a GET request with the request parameter “questionId” with questionId as the id of the question that the options will be belong to:
1 2 3 4 |
@GetMapping("") public Flux<Option> findByQuestionId(@RequestParam String questionId) { } |
then use the findByQuestionId() method that we defined in the OptionRepository interface to return as the following:
1 2 3 4 |
@GetMapping("") public Flux<Option> findByQuestionId(@RequestParam String questionId) { return optionRepository.findByQuestionId(questionId); } |
That’s it! Let’s test it!
Suppose, in the database I have the following options:
then when the request with questionId is 5ad5d9d651bd7a0aefa87fb3, the result will look like this:
For this API, since everything is Spring Data MongoDB Reactive, we do not need to write Unit Test for the code that we just added.