RestTemplate usage and implementation in Springboot

Posted By : Kundan Ray Akela | 12-Jan-2017

In this blog I am going to share the information about how to use RestTemplate in your spring project. So, let's start with basic information about RestTemplate.

It is the central Spring class for client-side HTTP access.It is very similar to the other Spring template example JdbcTemplate, JmsTemplate, and the various other templates found in the Spring Framework and other portfolio projects.RestTemplate is thread-safe once constructed, and  we can use callbacks to customize its operations.

RestTemplate Methods:
Http DELETE - delete(String, String...),Http GET -getForObject(String, Class, String...),Http HEAD-headForHeaders(String, String...),Http OPTIONS optionsForAllow(String, String...),Http POST - postForLocation(String, Object, String...),Http PUT-put(String, Object, String...)

For example, getForObject() will perform a GET, convert the HTTP response into an object type of our choice, and returns that object. postForLocation will do a POST, converting the given object into a HTTP request, and returns the response HTTP Location header where the newly created object can be found. As you can see, these methods try to enforce REST best practices.

We can pass URI as first argument in these methods and choose one of these methods to perform tasks based on our requirement. For example for performing HTTP GET request we can use getForObject() method that will perform GET and convert response into the object type of our choice and will return that object.

For expamle:

String response = restTemplate.getForObject("http://localhost/hotel/{hostelId}/bookings/{booking}", String.class, "12", "22");

will perform GET on  http://localhost/hostel/12/bookings/22. We can also pass parameters in Map.

Map parameters = new HashMap();
vars.put("hostelId", "12");
vars.put("booking", "22");
String response = restTemplate.getForObject("http://localhost/hotel/{hostelId}/bookings/{booking}", String.class, parameters);

Full example:

@SpringBootApplication
public class Application {

	private static final Logger log = LoggerFactory.getLogger(Application.class);

	public static void main(String args[]) {
		SpringApplication.run(Application.class);
	}

	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}

	@Bean
	public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
		return args -> {
			User user = restTemplate.getForObject(
					"http://localhost/api/user/{userId}", User.class,1);
			log.info(user.toString());
		};
	}
}

 

Your User.java will look like this:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {

    private String firstName;
     private String lastName;

    public User() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public Value getLastName() {
        return lastName;
    }

    public void setValue(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "User{" +
                "firstName='" + firstName + '\'' +
                ", lastName=" + lastName +
                '}';
    }
}

Thanks

Kundan Ray

About Author

Author Image
Kundan Ray Akela

Kundan holds years of industry experience as a Fullstack Developer in various technologies and is focused in defining the architecture of the system to ensure reliability and resilience. He possess good knowledge & understanding of latest technologies and hands-on experience in Core Java, Spring-Boot, hibernate, React, Angular , Apache Kafka messaging queue , AI Development like Computer Vision/Generative AI/Prediction System, Internet of Things based technologies and relational database like MySql, PostgreSQL etc. He is proficient in API Implementations, Webservices, Development Testings and deployments, code enhancements and have been contributing to company values through his deliverable in various client projects namely VirginMedia, Konfer, TIHM, Herdsy, HP1T and many more. He has a creative mind and has good analytical skills and likes reading and exploring new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..