Questions Management – API Category Service – Build API adding new category using Spring WebFlux

Check out the full series of Questions Management tutorial here.

Unlike the Core Category Service, the API Category Service only receives a request and then calls the Core Category Service to perform this request. Therefore, in order to build API adding new category in API Category Service, there are a few things we have to do first.

The first thing we need to do is add a new Category object to contain the category information.

Because the API Category Service will call to the Core Category Service, so I will configure the Core Category Service information in the application.properties file as follows:

To handle the call to the Core Category Service, I will create an interface called CoreCategoryService:

with the implementation is CoreCategoryServiceImpl:

As you can see, in the CoreCategoryServiceImpl class, I’ve injected information about the base URL of the Core Category Service.

I will run this service using port 8282 so I will also add the server.port property in the application.properties file as follows:

OK, everything is ready, now I will go to the main part of this tutorial.



Similar to the Core Category Service, I will create a controller named CategoryController with the following content:

With this declaration, I also expose APIs for the API Category Service with the request URL that starts with “/category”.

Next, we will inject CoreCategoryService into CategoryController to use:

To build API adding new category, I will add a new method in the CoreCategoryService class named:

with implementation as follows:

As you can see, here I have used the WebClient object to connect to the Core Category Service and call the API adding new category of this service with the URI “/category/add”.

Then I will add a new method in CategoryController to expose a POST request “/add” with the data in the body as a Category object:

Our task is to simply call the save() method of CoreCategoryService:

At this point we have completed building a new API for adding new category for the API Category Service, let’s test it.

Questions Management - API Category Service - Build API adding new category using Spring WebFlux


The last thing we need to do is add a new Unit Test to the code that we just added.

I will create a class named CategoryControllerTest located in the src/test/java folder, com.huongdanjava.categoryservice package to test the CategoryController class.

Next, I will mock the CoreCategoryService object and inject it into CategoryController as follows:

To use mock objects, we have to initialize them before running one test case, so we will add a method with the JUnit @Before annotation as follows:

The code to test the createCategory() method is as follows:

Run “Maven test” in STS or “mvn test” with Apache Maven, you will not see any errors.

Add Comment