RestTemplate
Synchronous Communication
Learn how one microservice can communicate with another microservice using HTTP and RestTemplate.
What You'll Learn
- 1. Introduction
- 2. Setting Up Two Microservices
- 3. What is Synchronous Communication?
- 4. HTTP Request and Response
- 5. Calling REST API Using Plain Java
- 6. RestTemplate
- 7. RestTemplate Configuration
- 8. GET Request Example
- 9. RestTemplate Methods
- 10. exchange() Method
- 11. execute() Method
- 12. Common Mistakes
- 13. Best Practices
- 14. Interview Questions
- 15. PDF Notes
- 16. Frequently Asked Questions
- 17. Conclusion
- 18. Related Articles
1. Introduction
In a microservices architecture, one service often needs to communicate with another service. One approach is synchronous communication, where the client waits for the server response before continuing.
The example in this article uses an OrderService and a ProductService running on different port numbers.
2. Setting Up Two Microservices
The example uses two Spring Boot microservices:
- OrderService — client service
- ProductService — target service
The two services run on different port numbers. OrderService makes a request to ProductService.
server.port=8081
server.port=8082
3. What is Synchronous Communication?
In synchronous communication, the client waits for the server response before continuing. The communication is blocking in nature because the calling thread waits for the response.
Synchronous Communication Types in Spring Boot
- RestTemplate
- RestClient
- FeignClient
These are commonly used approaches for synchronous service-to-service HTTP communication.
4. HTTP Request and Response
Before using RestTemplate, it is useful to understand the basic HTTP request and response flow.
Example HTTP GET Request
GET /orders/1 HTTP/1.1
Host: localhost:8081
Accept: application/json
Example HTTP POST Request
POST /products HTTP/1.1
Host: localhost:8081
Content-Type: application/json
Accept: application/json
{
"name": "Ice-Cream",
"price": 100
}
Keep-Alive
HTTP/1.1 can reuse a connection for multiple requests when keep-alive behavior is enabled. Connection idle timeout and maximum request settings depend on the client and server configuration.
5. Calling REST API Using Plain Java
A REST endpoint can be called using Java's HttpURLConnection directly. However, this requires more low-level request and connection handling.
@RestController
@RequestMapping("/orders")
public class OrderController {
@GetMapping("/{id}")
public ResponseEntity<String> getOrder(
@PathVariable String id) {
HttpURLConnection connection = null;
try {
String url =
"http://localhost:8082/products/" + id;
URL obj = new URL(url);
connection =
(HttpURLConnection)
obj.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty(
"Accept",
"application/json"
);
connection.setConnectTimeout(100);
connection.setReadTimeout(500);
BufferedReader in =
new BufferedReader(
new InputStreamReader(
connection.getInputStream()
)
);
StringBuilder response =
new StringBuilder();
String responseLine;
while (
(responseLine = in.readLine()) != null
) {
response.append(responseLine);
}
in.close();
return ResponseEntity.ok(
response.toString()
);
} catch (Exception e) {
return ResponseEntity
.internalServerError()
.body("Error");
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
Problems With the Low-Level Approach
- More boilerplate code
- Manual request and response handling
- Manual connection handling
- Manual response processing
- Less convenient for common REST operations
6. What is RestTemplate?
RestTemplate provides a higher-level abstraction for calling REST APIs from Spring applications. Instead of directly creating and managing HttpURLConnection objects, developers can use methods such as getForObject(), getForEntity(), postForObject(), put() and delete().
RestTemplate is a traditional synchronous HTTP client abstraction used in Spring applications.
7. RestTemplate Configuration
A RestTemplate instance can be exposed as a Spring bean.
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Configuring Timeouts
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory =
new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(1000);
factory.setReadTimeout(5000);
return new RestTemplate(factory);
}
}
SimpleClientHttpRequestFactory can be used when connection and read timeout values need to be configured.
8. GET Request Using RestTemplate
The getForObject() method can be used when the application needs the response body as an object.
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/{id}")
public ResponseEntity<String> getOrder(
@PathVariable String id) {
String response =
restTemplate.getForObject(
"http://localhost:8082/products/" + id,
String.class
);
System.out.println(
"Response from Product API: "
+ response
);
return ResponseEntity.ok(
"order call successful"
);
}
}
The example demonstrates the OrderService to ProductService flow using getForObject().
9. Common RestTemplate Methods
| Method | Purpose | Example |
|---|---|---|
| getForObject() | Returns the response body as an object. | restTemplate.getForObject(...) |
| getForEntity() | Returns ResponseEntity with response information. | restTemplate.getForEntity(...) |
| postForObject() | Sends POST and returns response body. | restTemplate.postForObject(...) |
| postForEntity() | Sends POST and returns ResponseEntity. | restTemplate.postForEntity(...) |
| put() | Sends a PUT request. | restTemplate.put(...) |
| delete() | Sends a DELETE request. | restTemplate.delete(...) |
| exchange() | Customizes HTTP method, headers and request body. | restTemplate.exchange(...) |
| execute() | Provides more direct control over request and response processing. | restTemplate.execute(...) |
These methods provide different levels of control over HTTP requests and responses.
10. Using exchange()
exchange() is useful when you need more control over the HTTP method, headers and request body.
String url =
"http://localhost:8080/api/products";
HttpHeaders headers =
new HttpHeaders();
headers.setContentType(
MediaType.APPLICATION_JSON
);
headers.set(
"Authorization",
"Bearer my-token"
);
Product product =
new Product();
product.setName("Ice-cream");
product.setPrice(100);
HttpEntity<Product> requestEntity =
new HttpEntity<>(
product,
headers
);
ResponseEntity<Product> response =
restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
Product.class
);
Product result =
response.getBody();
HttpStatus status =
response.getStatusCode();
exchange() allows the HTTP method, headers, request entity and response type to be specified.
11. Using execute()
When more direct control is required, execute() can work with RequestCallback and ResponseExtractor.
RestTemplate restTemplate =
new RestTemplate();
String url =
"http://localhost:8080/api/products";
RequestCallback requestCallback =
request -> {
request.getHeaders()
.setContentType(
MediaType.APPLICATION_JSON
);
Product product =
new Product(
"Ice-cream",
100
);
ObjectMapper mapper =
new ObjectMapper();
byte[] body =
mapper.writeValueAsBytes(product);
StreamUtils.copy(
body,
request.getBody()
);
};
ResponseExtractor<String>
responseExtractor =
response -> {
return StreamUtils.copyToString(
response.getBody(),
StandardCharsets.UTF_8
);
};
String response =
restTemplate.execute(
url,
HttpMethod.POST,
requestCallback,
responseExtractor
);
System.out.println(
"response is: " + response
);
RequestCallback can customize the outgoing request, while ResponseExtractor can control how the response is read and converted.
12. Common Mistakes
Things to Check
- Using the wrong ProductService port
- Incorrect endpoint URL
- Incorrect HTTP method
- Incorrect request or response type
- Missing request headers
- Missing connection/read timeout configuration
- Not handling unsuccessful HTTP responses
13. Best Practices
Recommended Practices
- Configure appropriate connection and read timeouts.
- Keep service URLs configurable.
- Use suitable request and response types.
- Handle unsuccessful HTTP responses explicitly.
- Use centralized configuration where appropriate.
- Choose the communication client according to application requirements.
14. RestTemplate Interview Questions
15. RestTemplate PDF Notes
RestTemplate – Synchronous Communication
Get the complete RestTemplate notes, including microservice communication, RestTemplate methods, examples and interview preparation material.
Unlock PDF Download
Watch the related Chai With Code video first. After returning to this article, an 8-second countdown will run and the PDF download button will be unlocked.
Returning from the video...
PDF Unlocked
Your RestTemplate PDF is now unlocked. Click the button below to open the PDF on Google Drive.
Open PDF Download16. Frequently Asked Questions
17. Conclusion
RestTemplate provides an abstraction for synchronous HTTP communication from Spring applications. It supports common operations such as GET, POST, PUT and DELETE and also provides customizable methods such as exchange() and execute().
The article demonstrates the progression from low-level HttpURLConnection communication to RestTemplate-based communication between OrderService and ProductService.
The article also introduces the limitations of the traditional RestTemplate approach and discusses newer HTTP client options available in Spring.