liveBook · Manning

RestTemplate

As explained in Spring Start Here, Second Edition

RestTemplate is a Spring HTTP client API for synchronously sending requests and receiving responses from remote services.

RestTemplate is a Spring API for making synchronous calls to REST endpoints. It remains useful to recognize in older projects, but newer applications are directed toward other client options. section 11.3 section 11.6

A typical call is assembled in three steps:

  • Create and configure HttpHeaders for the request. section 11.3
  • Put the request body and headers into an HttpEntity. section 11.3
  • Call exchange() with the URI, HTTP method, entity, and response type, then use the response. section 11.3
Listing 11.7 The app’s PaymentsProxy calling the /payment endpoint
@Component
public class PaymentsProxy {
 
  private final RestTemplate rest; 
 
  @Value("${name.service.url}")
  private String paymentsServiceUrl;    #A
 
  public PaymentsProxy(RestTemplate rest) {    #B
    this.rest = rest;
  }
 
  public Payment createPayment(Payment payment) {
    String uri = paymentsServiceUrl + "/payment";
 
    HttpHeaders headers = new HttpHeaders();      #C
    headers.add("requestId",                      #C
                UUID.randomUUID().toString());    #C
 
    HttpEntity<Payment> httpEntity =     #D
      new HttpEntity<>(payment, headers);
 
    ResponseEntity<Payment> response =     #E
        rest.exchange(uri,                 #E
            HttpMethod.POST,               #E
            httpEntity,                    #E
            Payment.class);                #E
 
    return response.getBody();   #F
  }
}

The payment proxy listing shows the request ID header and payment body being assembled before a POST call through exchange(). section 11.3

How Spring Start Here, Second Edition covers it

How deep it goes
Shows a payment call using headers, HttpEntity, exchange(), and a response, while noting retries and fallbacks as harder to implement.
Examples
Demonstrates a payment-service POST carrying a requestId header and a Payment body.
What you can do after
Apply it to implement a payment-service call by assembling headers and a body, invoking exchange(), and using the response.
How it connects
Connects REST endpoint consumption with HTTP headers, HttpEntity, exchange(), RestClient, OpenFeign, and WebClient.

Also explained in

Compare how 3 books explain RestTemplate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.