Chai With Code
  • Home
  • About Us
  • Contact Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
Type Here to Get Search Results !
HomeSpring BootRestTemplate in Spring Boot – Synchronous Communication Between Microservices

RestTemplate in Spring Boot – Synchronous Communication Between Microservices

Mohan September 20, 2026 0
Learn how RestTemplate can be used for synchronous communication between Spring Boot microservices. This guide covers OrderService and ProductService, HTTP communication, RestTemplate configuration, common methods, practical examples and limitations.
September 20, 2026 15 min read Spring Boot Microservices RestTemplate Interview
Spring Boot • Microservices

RestTemplate
Synchronous Communication

Learn how one microservice can communicate with another microservice using HTTP and RestTemplate.

REST

What You'll Learn

What is synchronous communication?
OrderService and ProductService setup
HTTP request and response flow
Calling APIs using RestTemplate
RestTemplate configuration
GET, POST, PUT and DELETE methods
exchange() and execute()
Common mistakes and limitations
Interview questions
PDF revision notes
Table of Contents
  • 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.

OrderService - application.properties
server.port=8081
ProductService - application.properties
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

HTTP
GET /orders/1 HTTP/1.1
Host: localhost:8081
Accept: application/json

Example HTTP POST Request

HTTP
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.

Java
@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.

Java
@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {

        return new RestTemplate();

    }

}

Configuring Timeouts

Java
@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.

Java
@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"
        );

    }

}
Example Output
Response from Product API: Product fetched with id: 1 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.

Java
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.

Java
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

1. What is RestTemplate?
RestTemplate is a Spring client abstraction used to perform HTTP requests to REST endpoints.
2. What is the difference between getForObject() and getForEntity()?
getForObject() returns the response body converted to the requested type. getForEntity() returns ResponseEntity containing response information such as status and headers.
3. How can you configure RestTemplate?
A RestTemplate can be registered as a Spring bean. A request factory can also be configured when connection and read timeouts are required.
4. What is exchange() used for?
exchange() is useful when you need to customize the HTTP method, headers, request entity and expected response type.
5. What is execute() used for?
execute() provides more direct control through RequestCallback and ResponseExtractor.
6. What are some limitations of RestTemplate?
RestTemplate has many overloaded methods and is generally considered a traditional Spring HTTP client. Newer Spring applications may also use newer HTTP client APIs depending on their requirements.

15. RestTemplate PDF Notes

RestTemplate – Synchronous Communication

Get the complete RestTemplate notes, including microservice communication, RestTemplate methods, examples and interview preparation material.

PDF

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.

8

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 Download

16. Frequently Asked Questions

What is synchronous communication?
In synchronous communication, the client waits for the server response before continuing.
What is RestTemplate used for?
RestTemplate can be used by a Spring application to make HTTP calls to REST APIs.
What is getForObject()?
It performs a GET request and converts the response body into the requested Java type.
What is getForEntity()?
It performs a GET request and returns a ResponseEntity containing response information.
Why use exchange()?
exchange() is useful when the HTTP method, headers, request entity and response type need more explicit control.
Is RestTemplate the only option for REST calls?
No. Spring applications can use different HTTP client approaches depending on the Spring version, application requirements and communication style.

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.

18. Related Articles

RestClient in Spring Boot

Learn the newer fluent-style REST client.

Feign Client in Spring Boot

Learn declarative REST communication between microservices.

Microservice Communication

Understand synchronous and asynchronous communication patterns.

Spring Boot Microservices

Learn microservice architecture with Spring Boot.

Tags
Backend Development Interview Java Microservices REST API RestTemplate Spring Boot
  • Newer

    RestTemplate in Spring Boot – Synchronous Communication Between Microservices

  • Older

    RestTemplate in Spring Boot – Synchronous Communication Between Microservices

You may like these posts

Post a Comment

0 Comments

Modules

  • Java Basics
  • SOLID Principles in Java
  • Java Design Patterns
  • Java8 Features
  • Spring Framework
  • Spring Boot Framework
  • Microservices
  • Kafka
  • Redis
  • Spring Security
  • Database
  • DevOps

Popular Posts

RestTemplate in Spring Boot – Synchronous Communication Between MicroservicesSeptember 20, 2026

Chai With Code

About Us

Welcome to Chai With Code — a developer-focused platform created to make software development concepts easier to understand, practice, and apply. We share practical programming tutorials, development guides, interview preparation resources, coding examples, and learning materials for developers who want to strengthen their technical skills.
  • Home
  • About
  • Contact us
  • Privacy Policy
Developed by ❤️ - Blogger Templates at Piki Templates © 2026Powered by CHAI with Code

Contact Form