RestTemplate Getforobject

By | | Updated : 2021-10-15 | Viewed : 177 times

Resttemplate Getforobject

We learned about postForObjec() and postForEntity in previous tutorial. It is time to explore the getForObject() method. So lets div into the topic.

Resttemplate Getforobject

getForObject() is used to retrieve the object from other microservice using a specific URL. Spring boot provides three types of methods for getForObject(). Please find given below.

Different types of getForObject() methods
T getForObject(String url, Class<T> responseType, Map<String,?> uriVariables)
T getForObject(String url, Class<T> responseType, Object... uriVariables)
T getForObject(URI url, Class<T> responseType)

Now we will see the nice examples for the above methods.

Resttemplate Getforobject Example

We will explore the different types of methods of getForObject(). See the below-given sections.

RestTemplate Getforobject With Parameters

restTemplate Client: RestTemplate Getforobject With Parameters
    //Using GetForObject with Parameters
    public CustomerDetails getCustDetailsGetForObject(Long id) {
        Map<String, Object> requestMap = new HashMap();
        requestMap.put("id", id);
        return restTemplate.getForObject("http://localhost:8082/restTemplateServer/api/customerDetails/{id}", CustomerDetails.class, requestMap);
restTemplate Server: RestTemplate Getforobject With Parameters
    public ResponseEntity<?> getCustomerDetails(@PathVariable Long id) {
        CustomerDetails customerDetails = customerDetailsServiceImpl.getCustomerDetails(id);
        return ResponseEntity.ok(customerDetails);

So here we used getForObject() with URI variables. So these variables are used as path variables in other microservices. Here you can see the id used as URI variable in the getForObject() methods.

RestTemplate Getforobject

Notice below given example for getForObject(). Here it does not have URI variables.

restTemplate Client: RestTemplate Getforobject Without Parameters
  //Using GetForObject
    public List<CustomerDetails> getCustDetailsUsingGetForObject() {
        return restTemplate.getForObject("http://localhost:8082/restTemplateServer/api/customerDetails", List.class);
restTemplate Server: RestTemplate Getforobject Without Parameters
    public ResponseEntity<?> getCustomerDetails() {
        List<CustomerDetails> CustomerDetailList = customerDetailsServiceImpl.getCustomerDetails();
        return ResponseEntity.ok(CustomerDetailList);

So when client microservice request for the object using getForObject() the server microservice provide the data.

GitRepo is here SpringBoot-RestTemplate-Example-App for exploring the entire code base.

Leave A Reply