📌 Why Build a REST Client?
✅ Automates API testing inside the application.
✅ Eliminates the need for external tools like Postman.
✅ Useful for microservices communication.
✅ Provides a programmatic way to consume REST APIs.
🚀 Step 1: Add WebClient Dependency to pom.xml
📌 Ensure the spring-boot-starter-webflux
dependency is added
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
WebClient is a non-blocking, reactive alternative to RestTemplate that supports asynchronous and synchronous calls.
🚀 Step 2: Configure WebClient
To make API calls, we must define a base URL for our User Management REST API.
📌 Create WebClientConfig.java
inside net.javaguides.usermanagement.client
package net.javaguides.usermanagement.client;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class WebClientConfig {
@Bean
public WebClient webClient(WebClient.Builder builder) {
return builder.baseUrl("http://localhost:8080/api/users").build();
}
}
📌 Explanation
✔️ @Configuration
→ Marks this class as a Spring configuration file.
✔️ Defines a WebClient
Bean that connects to http://localhost:8080/api/users
.
✔️ Centralized configuration allows easy URL modification.
🚀 Step 3: Implement the REST Client
Now, let's create a REST Client that will:
✅ Create a new user
✅ Fetch a user by ID
✅ Fetch all users
✅ Update a user
✅ Delete a user
📌 Create RESTClient.java
inside net.javaguides.usermanagement.client
package net.javaguides.usermanagement.client;
import net.javaguides.usermanagement.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.time.LocalDate;
import java.util.List;
@Component
public class RESTClient {
@Autowired
private WebClient webClient;
// Create a new user
public UserDto createUser() {
UserDto newUser = new UserDto(
null,
"Ravi",
"Kumar",
"ravi.kumar@example.com",
LocalDate.of(1995, 8, 15)
);
return webClient.post()
.body(Mono.just(newUser), UserDto.class)
.retrieve()
.bodyToMono(UserDto.class)
.block(); // Blocking for simplicity (not recommended in production)
}
// Get user by ID
public UserDto getUserById(Long id) {
return webClient.get()
.uri("/{id}", id)
.retrieve()
.bodyToMono(UserDto.class)
.block();
}
// Get all users
public List<UserDto> getAllUsers() {
return webClient.get()
.retrieve()
.bodyToFlux(UserDto.class)
.collectList()
.block();
}
// Update a user by ID
public UserDto updateUser(Long id) {
UserDto updatedUser = new UserDto(
id,
"Ravi",
"Kumar",
"ravi.updated@example.com",
LocalDate.of(1995, 8, 15)
);
return webClient.put()
.uri("/{id}", id)
.body(Mono.just(updatedUser), UserDto.class)
.retrieve()
.bodyToMono(UserDto.class)
.block();
}
// Delete a user by ID
public void deleteUser(Long id) {
webClient.delete()
.uri("/{id}", id)
.retrieve()
.toBodilessEntity()
.block();
}
}
📌 Explanation of RESTClient.java
✔️ @Component
→ Registers this class as a Spring Bean.
✔️ Uses WebClient
to interact with the REST API.
✔️ block()
is used for simplicity but should be replaced with reactive programming in production.
🚀 Step 4: Create a CommandLineRunner to Test the Client
We need a way to execute our REST client when the application starts.
📌 Modify UserManagementApplication.java
inside net.javaguides.usermanagement
package net.javaguides.usermanagement;
import net.javaguides.usermanagement.client.RESTClient;
import net.javaguides.usermanagement.dto.UserDto;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserManagementApplication implements CommandLineRunner {
private final RESTClient restClient;
public UserManagementApplication(RESTClient restClient) {
this.restClient = restClient;
}
public static void main(String[] args) {
SpringApplication.run(UserManagementApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("------ REST Client Test Started ------");
// Create a user
UserDto createdUser = restClient.createUser();
System.out.println("Created User: " + createdUser);
// Get user by ID
UserDto retrievedUser = restClient.getUserById(createdUser.id());
System.out.println("Retrieved User: " + retrievedUser);
// Get all users
System.out.println("All Users: " + restClient.getAllUsers());
// Update the user
UserDto updatedUser = restClient.updateUser(createdUser.id());
System.out.println("Updated User: " + updatedUser);
// Delete the user
restClient.deleteUser(createdUser.id());
System.out.println("User Deleted Successfully");
System.out.println("------ REST Client Test Completed ------");
}
}
📌 Explanation
✔️ CommandLineRunner
executes the REST Client when the application starts.
✔️ Calls all CRUD methods and prints responses in the console.
🚀 Step 5: Run and Test the Application
📌 Start the Spring Boot application in IDE or use the following maven command:
mvn spring-boot:run
📌 Expected Console Output
🚀 Congratulations! You have successfully built and tested a REST Client in Spring Boot! 🎯
🎯 Summary: What We Achieved
✔️ Created a WebClient-based REST Client to test APIs.
✔️ Automated API testing instead of using Postman.
✔️ Executed CRUD operations using our custom client.
✔️ Printed the API responses to the console.
🎉 Now you can use this REST Client to test any Spring Boot REST API! 🚀🔥
Comments
Post a Comment
Leave Comment