Tutorials Spring Boot How to Consume REST API in Spring Boot Using RestTemplate?

How to Consume REST API in Spring Boot Using RestTemplate?

RestTemplate makes it very convenient to call the remote REST services from the Spring Boot application. It is a synchronous client and is designed to make standard HTTP calls like GET, POST, PUT, OPTIONS, and DELETE.

Following are some of the useful methods executing REST API calls:

  • getForObject(url, classType) – It retrieves a representation by doing a GET on the URL. The response (if any) is unmarshalled to given class type and returned.
  • getForEntity(url, responseType) – retrieve a representation as ResponseEntity by doing a GET on the URL.
  • exchange(url, httpMethod, requestEntity, responseType) – execute the specified RequestEntity and return the response as ResponseEntity.
  • execute(url, httpMethod, requestCallback, responseExtractor) – execute the http method to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.
Deprication Notice!!

A modern version of the HTTP client called WebClient has been introduced in Spring 5. It is an alternative to RestTemplate. It provides both synchronous and asynchronous API’s to make the REST calls more efficient.

If you’re developing a new application or migrating an old one, it is recommended to use WebClient over RestTemplate. RestTemplate will be deprecated in future versions.

Consuming the GET API

In the given example, we are fetching the API response as a JSON String. We need to use ObjectMapper to parse it to the POJO before using it in the application.

getForObject() method is pretty useful when we are getting an unparsable response from the server, and we have no
control to get it fixed on the server-side. Here, we can get the response as String, and use a custom parser or use a string replacement function to fix the response before handling it to the parser.

In the course of this tutorial, we will create simple RestTemplate bean in the application.

@Service
public class ProductService {

    private static final String POST_API = "https://fakestoreapi.com/products";
    private static final String GET_API = "https://fakestoreapi.com/products/{productId}";
    private static final String DELETE_API = "https://fakestoreapi.com/products/{productId}";

    private final RestTemplate restTemplate;

    public ProductService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }
}

Consuming APIs as String

Map<String, String> params = new HashMap<>();
params.put("productId", productId);
String result = restTemplate.getForObject(GET_API, String.class, params);

Consuming APIs response to POJO

Map<String, String> params = new HashMap<>();
params.put("productId", productId);

Product result = restTemplate.getForObject(GET_API, Product.class, params);

Using getForEntity() Method

Map<String, String> params = new HashMap<>();
params.put("productId", productId);
ResponseEntity<Product> result = restTemplate.getForEntity(GET_API, Product.class, params);

HttpStatus statusCode = result.getStatusCode();
Product product = result.getBody();

Sending HTTP Headers using RestTemplate

HttpHeaders headers = new HttpHeaders();
headers.setAccept(List.of(MediaType.APPLICATION_JSON));
headers.set("X-API-KEY", "YOUR_API_KEY");
HttpEntity<String> httpEntity = new HttpEntity<>(headers);

Map<String, String> params = new HashMap<>();
params.put("productId", productId);

ResponseEntity<Product> result = restTemplate.exchange(GET_API, HttpMethod.GET, httpEntity, 
                    Product.class, params);
return result.getBody();

Consuming the POST API

HttpHeaders headers = new HttpHeaders();
headers.set("X-API-KEY", "YOUR_API_KEY");
headers.setContentType(MediaType.APPLICATION_JSON);    
HttpEntity<Product> httpEntity = new HttpEntity<>(product, headers);
    
Product createdProduct = restTemplate.postForObject(POST_API, httpEntity, Product.class);

Consuming the PUT API

Map<String, String> params = new HashMap<>();
params.put("productId", product.getId());

restTemplate.put(GET_API, product, params);

Consuming the DELETE API

Map<String, String> params = new HashMap<>();
params.put("productId", productId);

restTemplate.delete(GET_API, params);
Total
1
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post

How to Execute Code on Spring Boot Application Startup?

Next Post

How to Change Spring Boot Default Port?

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x