📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Video Tutorial
What we will build
Step1: Download source code from GitHub repository and import in your IDE
Please refer Spring Boot 2 JPA MySQL CRUD Example article to build a complete spring boot CRUD Rest APIs application. You can download the source code of this article from my GitHub repository - https://github.com/RameshMF/spring-boot2-jpa-crud-example. You can import this project in your IDE and make sure that it is up and running.Step 2: Spring Rest Controller - EmployeeController.java
package net.guides.springboot2.springboot2jpacrudexample.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.guides.springboot2.springboot2jpacrudexample.exception.ResourceNotFoundException;
import net.guides.springboot2.springboot2jpacrudexample.model.Employee;
import net.guides.springboot2.springboot2jpacrudexample.repository.EmployeeRepository;
@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
Step 3: Spring REST Client GET, POST, PUT and DELETE using RestTemplate
package net.guides.springboot2.springboot2jpacrudexample; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import net.guides.springboot2.springboot2jpacrudexample.model.Employee; public class SpringRestClient { private static final String GET_EMPLOYEES_ENDPOINT_URL = "http://localhost:8080/api/v1/employees"; private static final String GET_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}"; private static final String CREATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees"; private static final String UPDATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}"; private static final String DELETE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}"; private static RestTemplate restTemplate = new RestTemplate(); public static void main(String[] args) { SpringRestClient springRestClient = new SpringRestClient(); // Step1: first create a new employee springRestClient.createEmployee(); // Step 2: get new created employee from step1 springRestClient.getEmployeeById(); // Step3: get all employees springRestClient.getEmployees(); // Step4: Update employee with id = 1 springRestClient.updateEmployee(); // Step5: Delete employee with id = 1 springRestClient.deleteEmployee(); } private void getEmployees() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity < String > entity = new HttpEntity < String > ("parameters", headers); ResponseEntity < String > result = restTemplate.exchange(GET_EMPLOYEES_ENDPOINT_URL, HttpMethod.GET, entity, String.class); System.out.println(result); } private void getEmployeeById() { Map < String, String > params = new HashMap < String, String > (); params.put("id", "1"); RestTemplate restTemplate = new RestTemplate(); Employee result = restTemplate.getForObject(GET_EMPLOYEE_ENDPOINT_URL, Employee.class, params); System.out.println(result); } private void createEmployee() { Employee newEmployee = new Employee("admin", "admin", "admin@gmail.com"); RestTemplate restTemplate = new RestTemplate(); Employee result = restTemplate.postForObject(CREATE_EMPLOYEE_ENDPOINT_URL, newEmployee, Employee.class); System.out.println(result); } private void updateEmployee() { Map < String, String > params = new HashMap < String, String > (); params.put("id", "1"); Employee updatedEmployee = new Employee("admin123", "admin123", "admin123@gmail.com"); RestTemplate restTemplate = new RestTemplate(); restTemplate.put(UPDATE_EMPLOYEE_ENDPOINT_URL, updatedEmployee, params); } private void deleteEmployee() { Map < String, String > params = new HashMap < String, String > (); params.put("id", "1"); RestTemplate restTemplate = new RestTemplate(); restTemplate.delete(DELETE_EMPLOYEE_ENDPOINT_URL, params); } }
Hi This is a nice blog for restTeamplate i also cover this topic you can review the blog at
ReplyDeletehttps://www.javadream.in/resttemplate-in-spring-boot-microservice/