RestTemplate used to be a standard when it came to consuming RESTful services. But when if you visit the documentation page of RestTemplate you can find a note saying that it is in maintenance mode and it is preferred to use the new WebClient.
So how to get started with WebClient ?
Before starting I assume you have done some hands on with Spring Boot and have proper understanding of how REST APIs work.
Let's get started.
I have created a maven project called producer
whose controller file looks like this:
We will create a separate project called consumer
to consume the APIs of producer
.
I have used spring initializr (https://start.spring.io/) to create the projects having dependencies Spring Web and Spring Reactive Web.
Please feel free to play around the above controller as we are going to consume every API written over here. I would suggest you to use Postman or cURL.
We will call the controller for consumer class as ConsumerController.java and do some initialisation.
GET Avengers API
retrieve
performs the HTTP request and retrieves the response body.
bodyToMono
extracts the body to a Mono
which is the Reactive equivalent of CompletableFuture type. We are specifying that whatever body you get from retrieve
convert it to an instance of type HashMap
and return it in future.
block
is very important here as it converts the calls from asynchronous to synchronous. Here it says unless, bodyToMono
returns something block the flow.
Similarly we can write GET Avenger API
Response contains String
object that's why we are using bodyToMono(String.class)
.
PUT Avenger API
Notice how we are using uri
field differently here. We are using builder pattern to generate uri with required path & query parameters.
exchange
exchanges the given request for a response mono. It is similar to retrieve
but provides better control over response.
DELETE Avenger API
POST Avenger API
BodyInserters.fromProducer
allows us to pass requestMap in body
. The first argument here is a Mono
of requestMap while second argument is class type for the object passed in Mono.just
.
Now, just test it out using Postman or cURL. Don't forget to have different ports for producer and consumer.
Github Repo Link: https://github.com/Nishant-Ingle/WebClient-CRUD