EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot RestTemplate
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot RestTemplate

Spring Boot RestTemplate

Definition of Spring Boot RestTemplate

In Spring boot we can make use of RestTemplate which helps us to invoke the PAI from the application itself, we can write method which invoke the API from it to consume the data and for further processing. RestTemplate is present inside the started-web dependency of spring boot. If we want to use it we can simply auto wired its object and use its different methods available to make any type of request from the application. By the use of it we can perform get, post, put, delete any request. But from spring boot newer version it is going to deprecate soon, and they have come up with webclient to use as an alternative for this. But in this tutorial we will see how to implement RestTemplate and make use of it, to invoke the APIS for better understating of the implementation for beginners.

Syntax:

As we know that it is a mechanism we can say to call the HTTP endpoints using the RestTemplate, by making some small configurations and few lines of code. Let’s take a closer look at the syntax for better understating of its usage see below;

@Autowired
private RestTemplate name_of_variable;

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

As you can see in the above syntax we make this line of code to use the RestTemplate inside the program to invoke any URL. Let’s take an closer look at the practice syntax for better understating, see below;

Example:

public class Test{
@Autowired
private RestTemplate restTemplate;
}

In this way we can use this RestTemplate inside the spring boot class, in the coming section of the tutorial we will see more details configuration which is required to make this work, also how to invoke the API using RestTemplate in our application.

How Spring Boot RestTemplate Works?

As we already know that when to use RestTemplate in our application , suppose we have one scenario where i want to gather the data from third API or we can say my application which s running on differ server, so in order to get the data from differ server we would require to have make an HTTP request toward that server, once we make the request it will return us the data we want, also we should be aware about the URL we want to hit from our application. So in such scenario where we have to make HTTP request in order to get or send the data we can use RestTemplate, we should also know the method type because while writing code for restTemplate we have to use appreciate methods to invoke the API and have to pass all the required parameters as well as part of the URL only. In this section we will first see the required configuration that we have to make in order to run this application let’s get started;

  • Web Dependency: To make use of resttemplate we have to use this web dependency because it contain the required packages for this. So while creating the application or project add this dependency also.
  • Auto Wiring: After this we have to auto-wire the RestTemplate object inside our program where we want to make an RestTemplate call toward an URL. this is very normal and simple like we do for other component and services, we have application. So spring container now will take care of all the dependency for us, we do not need to make this explicitly.
  • Method: we can make one method inside which we can write the logic to use Rest Template to call the endpoint. It has so many different method to make the different type of call, let’s take an closer look at each of them in detail see below;
  • First we have to auto wire the RestTemplate object inside the class we want to make use of RestTemplate, after this we can use the below method to call the API,

Example:

final HttpEntity<String> request = new HttpEntity<>(json.toString(), your_headers);
ResponseEntity<String> response = this.restTemplate.exchange(your_URL, HttpMethod.POST, your-REQUEST, class_type.class);

As you can see i the above code we are making use of exchange method here, but it takes many parameters as the input here. We can also pass the headers inside it, to validate the URL at other side. Let’s first discuss the parameters t take;

  • URL: it specify the URL or API endpoint we want to hit from our application to get or post the data depended on the requirement.
  • Method Type: second parameter here specify the type of the Method it is.
  • request : third parameters is the request means the HttpEntity object which contain the parameters of URL or headers.
  • Class Type: Last parameters specify the type of response it will return.

Examples of Spring Boot RestTemplate

In this example we are just writing the rest template method to get the data response from the URL we have. You can replace the parameters with your, and try to hit the method by using test class or any advanced rest client. Everything should be in place to run this.

Code:

import com.scania.coc.core.common.handler.RestTemplateResponseErrorHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RestTemplateDemo {
private static final Logger logger = LoggerFactory.getLogger(RestTemplateDemo.class);
@Autowired
private String postEntity(String url, JSONObject json) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
final HttpEntity<String> request = new HttpEntity<>(json.toString(), headers);
ResponseEntity<String> response = this.restTemplate.exchange(url, HttpMethod.GET, request, String.class);
if (response.getStatusCode().equals(HttpStatus.OK)) {
System.out.println("got response succsessfully");
}
return "";
}
}

  • Main class should be like below;

Code:

@SpringBootApplication
@EnableScheduling
@EnableJpaRepositories
public class TestApplication{
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(TestApplication.class, args);
}
}

  • run application it should run without any error;

Output:

Output

Conclusion

By the use of RestTemplate we are able to invoke the API from our application, also we can get data from third party or other application if we have any dependency. So basically it is used to make the REST call to the application. These are very easy to use and handle by the developers as well without less configuration needed.

Recommended Articles

This is a guide to Spring Boot RestTemplate. Here we also discuss the introduction and key points on qualify along with examples. You may also have a look at the following articles to learn more –

  1. Spring cloud stream
  2. Spring Boot Dependencies
  3. Spring Boot Repository
  4. Spring Boot Profiles
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more