Spring Boot RestClient PUT Request Example

In this tutorial, we will learn how to use the RestClient class to make HTTP PUT requests. We will first create an Update Employee REST API using Spring Boot, Spring Data JPA, and MySQL database and then we will use the RestClient class to consume the Update Employee REST API.

The RestClient class is a new addition to Spring Framework 6.1 and Spring Boot 3.2. It provides a functional style blocking HTTP API that is similar in design to WebClient. RestClient is designed to be simpler and easier to use than RestTemplate, and it offers several advantages over RestTemplate, including: 

  • A fluent API that makes it easy to chain requests together 
  • Support for annotations to configure requests 
  • Built-in error handling 
  • Support for both blocking and non-blocking requests

Spring Boot RestClient PUT Request Example

Let's first create an Update Employee REST API using Spring Boot, Spring Data JPA, and MySQL database.

1. Add Maven Dependencies

Spring Boot provides a web tool called Spring Initializer to create and bootstrap Spring boot applications quickly. Just go to https://start.spring.io/ and generate a new spring boot project.

Open the pom.xml file and add the below Maven dependencies to the project:
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

2. Configure MySQL Database 

Let's first create a database, go to MySQL workbench, and use the below SQL query to create a new database: 
create database employee_management 
Next, open the application.properties file and add the following properties to it.
spring.datasource.url=jdbc:mysql://localhost:3306/employee_management
spring.datasource.username=root
spring.datasource.password=Mysql@123

# Hibernate properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
# create, create-drop
spring.jpa.hibernate.ddl-auto=update
Make sure that you change the spring.datasource.username & spring.datasource.password properties as per your MySQL installation.
The property spring.jpa.hibernate.ddl-auto is used for database initialization. I’ve used the value “update” for this property to create the database tables automatically. 

3. Create an Employee JPA Entity 

Let's create an Employee class and add the following content to it:
import jakarta.persistence.*;
import lombok.*;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column(nullable = false)
    private String lastName;

    @Column(nullable = false, unique = true)
    private String email;
}
Note that we are using Lombok annotations to reduce the boilerplate code (getters/setters). 

4. Create Spring Data JPA Repository - EmployeeRepository 

Let's create an EmployeeRepository interface that extends JpaRepository:
import net.javaguides.springboot.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

5. Create DTO Class - EmployeeDto

Let's create an EmployeeDto class to transfer the data between the client and server:
import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class EmployeeDto {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
}

6. Create a Service Layer 

Let's implement the service layer, we will first create an interface and then its implementation class. 

Create EmployeeService Interface 

Let's create an EmployeeService interface and declare the following method:
import net.javaguides.springboot.dto.EmployeeDto;

import java.util.List;

public interface EmployeeService {
    EmployeeDto updateEmployee(EmployeeDto employeeDto);
}

Create UserServiceImpl Class

Let's create an EmployeeServiceImpl class that implements an EmployeeService interface methods:
import lombok.AllArgsConstructor;
import net.javaguides.springboot.converter.EmployeeConverter;
import net.javaguides.springboot.dto.EmployeeDto;
import net.javaguides.springboot.entity.Employee;
import net.javaguides.springboot.service.EmployeeService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeRepository employeeRepository;

    @Override
    public EmployeeDto updateEmployee(EmployeeDto employeeDto) {
        // we need to check whether employee with given id is exist in DB or not
        Employee existingEmployee = employeeRepository.findById(employeeDto.getId())
                .orElseThrow(() -> new IllegalArgumentException(
                        "Employee not exists with a given id : " + employeeDto.getId())
                );

        // convert EmployeeDto to Employee JPA entity
        Employee employee = EmployeeConverter.mapToEmployee(employeeDto);
        return EmployeeConverter.mapToEmployeeDto(employeeRepository.save(employee));
    }
}

7. Create Controller Layer - EmployeeController 

We’ll now create the REST APIs for creating, retrieving, updating, and deleting an Employee resource. Let's create an EmployeeController class and let's build CRUD REST APIs for an Employee resource:
package net.javaguides.springboot.controller;

import lombok.AllArgsConstructor;
import net.javaguides.springboot.dto.EmployeeDto;
import net.javaguides.springboot.service.EmployeeService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("api/employees")
public class EmployeeController {

    private EmployeeService employeeService;

    // build update employee REST API
    // http://localhost:8080/api/employees/1
    @PutMapping("{id}")
    public ResponseEntity<EmployeeDto> updateEmployee(@PathVariable("id") long id
            ,@RequestBody EmployeeDto employeeDto){
        employeeDto.setId(id);
        EmployeeDto updatedEmployee = employeeService.updateEmployee(employeeDto);
        return new ResponseEntity<EmployeeDto>(updatedEmployee, HttpStatus.OK);
    }
}

8. Running Spring Boot Application 

From your IDE, run the main entry point class that contains a main() method as a standalone. The main entry point class will start the Spring Boot project in an embedded Tomcat server on port 8080.

9. Consume the Update Employee REST API using the RestClient class

Creating a RestClient

To create a RestClient, you can use the RestClientBuilder class. The RestClientBuilder class allows you to configure the RestClient, such as setting the base URI, adding interceptors, and configuring timeouts.
public class RestClientTest {
    private final RestClient restClient;

    public RestClientTest() {
        restClient = RestClient.builder()
                .baseUrl("http://localhost:8080")
                .build();
    }
}
Similarly to RestTemplate or any other rest client, RestClient allows us to make HTTP calls with request methods. Let’s walk through different HTTP methods to create, retrieve, modify, and delete resources.

Use UPDATE to Update an Existing Resource 

Let's use RestClient.put() method to make an HTTP PUT request to update the existing Employee entity:
    @Test
    public void updateEmployee() {

        Long employeeId = 1L;

        EmployeeDto updatedEmployee = new EmployeeDto();
        updatedEmployee.setFirstName("Ramesh");
        updatedEmployee.setLastName("Fadatare");
        updatedEmployee.setEmail("ramesh@gmail.com");

        EmployeeDto result = restClient.put()
                .uri("/api/employees/{id}", employeeId)
                .contentType(MediaType.APPLICATION_JSON)
                .body(updatedEmployee)
                .retrieve()
                .body(EmployeeDto.class);

        System.out.println(result.toString());
    }

Conclusion 

The RestClient class is a powerful and easy-to-use tool for making HTTP requests in Spring Boot applications. It is a great alternative to RestTemplate and it is well-suited for modern Spring applications. 

I hope this tutorial has been helpful. Please let me know if you have any questions.

Comments