WebClient Series - Table of Contents
Part 1 : How to create Spring WebClient CRUD - GET, POST, PUT and DELETE Examples - [This article]
If you see the RestTemplate java docs, you will see this message:
NOTE: As of 5.0 this class is in maintenance mode, with only minor requests for changes and bugs to be accepted going forward. Please, consider using the org.springframework.web.reactive.client.WebClient which has a more modern API and supports sync, async, and streaming scenarios.
This simply means RestTemplate is no longer the recommended way to use. Spring recommends to use WebClient instead. Follow along for the step by step instructions on how to use WebClient to do GET, POST, PUT and DELETE requests.
1. Add dependencies in pom.xml
Let's start by bootstrapping our application using Spring Initializer by selecting
spring-boot-starter-webflux
dependency. Although, not mandatory, we selected devtools
and lombok
to ease our development process.loading...
2. Create WebClient configuration
Create a WebClient object with the required configuration. In this example, we will be calling a real world Rest API that is publicly available to everyone and free to use.
loading...
3. Create model object
loading...
4. Update the existing controller as below:
loading...
The above example shows GET, POST, PUT and DELETE examples using WebClient. Don't get carried away by the result type:
Mono
. Its just a reactive way of handling the results. Mono
is used for handling single results while Flux
is for multiple results like a list of objects.The output of GET, POST, PUT and DELETE requests should be similar to below.
Now that we have a working real world API using WebClient, in our next post, we will see how to test/mock this API using 4 different ways:
Mockito, MockWebServer, WebTestClient and WireMockServer
Thats all folks !! Happy coding. If you feel this helped you, keep supporting us by or or below or on the articles on social media.