REST Template:
- RestTemplate is a class in Spring framework that provides a convenient way to call RESTful APIs.
- It is a high-level API that helps you interact with RESTful web services by converting HTTP requests and responses into Java objects.
- It uses the Apache HttpClient under the hood to send HTTP requests.
- You can use RestTemplate to make GET, POST, PUT, DELETE, and other HTTP requests.
- It automatically converts JSON and XML responses into Java objects.
- You can also set headers, add parameters, handle exceptions, and configure timeouts.
- RestTemplate supports both synchronous and asynchronous execution.
- RestTemplate is thread-safe, so you can reuse a single instance across multiple requests.
- You can use RestTemplate with Spring MVC to provide RESTful services for your application.
- RestTemplate can be easily integrated with other Spring modules such as Spring Security and Spring Retry.
Below is the code for a simple Spring Boot REST template example to retrieve a car data:
- Car Entity Class (Car.java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.example.demo.entity; import lombok.Data; @Data public class Car { private int id; private String brand; private String model; private int year; private String color; } |
- Car Controller (CarController.java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.example.demo.entity.Car; @RestController public class CarController { @GetMapping("/cars/{id}") public Car getCar(@PathVariable int id) { RestTemplate restTemplate = new RestTemplate(); Car car = restTemplate.getForObject("http://localhost:8080/cars/" + id, Car.class); return car; } } |
- Main Application Class (SpringBootRestTemplateExampleApplication.java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestTemplateExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestTemplateExampleApplication.class, args); } } |
- Application properties file (application.properties):
1 2 |
server.port=8080 |
This is a simple example that uses the Spring Boot REST template to retrieve a car data based on the car id. You can run the application and test the endpoint by calling http://localhost:8080/cars/{id}
in your web browser or a REST client like Postman.