RestTemplate is Spring’s straightforward, synchronous REST client. It handles request creation, execution, response interpretation, object mapping, and common HTTP boilerplate when one Spring application consumes another application’s API. section 7.3
Create an instance directly or expose it as a Spring bean so client code can reuse it. section 7.3
Choose an operation according to the HTTP request and the response details you need:
- Use getForObject() to return a response body mapped to a Java domain object. section 7.3.1
- Use getForEntity() when the body and response metadata, such as headers, are needed through ResponseEntity. section 7.3.1
- Use put() to serialize an object into an HTTP PUT request; the method returns void. section 7.3.2
- Use delete() to remove a resource identified by a URL and optional URL variables. section 7.3.3
- Use postForObject(), postForLocation(), or postForEntity() to receive the created object, its Location URI, or both. section 7.3.4
Fetching an ingredient
A client can retrieve an ingredient by substituting an ID into the URL and deserializing the response into Ingredient: rest.getForObject("http://localhost:8080/ingredients/{id}", Ingredient.class, ingredientId). URL variables can instead be supplied with a Map or a constructed URI. section 7.3.1
Creating, updating, and deleting ingredients
A client can send an Ingredient with postForObject(), replace one with put(), or remove one with delete(). These methods use the same URL-variable patterns while differing in request and return behavior. section 7.3.2 section 7.3.3 section 7.3.4
Table 7.2 RestTemplate defines 12 unique operations, each of which is overloaded, providing a total of 41 methods. (view table figure)
Browse the operation table to compare RestTemplate’s twelve unique operations and their overloaded method forms. section 7.3
