Tutorial

Spring RestTemplate Example

Published on August 3, 2022
Default avatar

By Pankaj

Spring RestTemplate Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Spring RestTemplate provides a convenient way to test RESTful web services.

Spring RestTemplate

  • Spring RestTemplate class is part of spring-web, introduced in Spring 3.
  • We can use RestTemplate to test HTTP based restful web services, it doesn’t support HTTPS protocol.
  • RestTemplate class provides overloaded methods for different HTTP methods, such as GET, POST, PUT, DELETE etc.

Spring RestTemplate Example

Let’s look at Spring RestTemplate example where we will test REST web services created in Spring Data JPA article. Below table illustrates the URIs supported by this rest web service. .tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-baqh{text-align:center;vertical-align:top} .tg .tg-yw4l{vertical-align:top}

URI HTTP Method Description
/springData/person GET Get all persons from database
/springData/person/{id} GET Get person by id
/springData/person POST Add person to database
/springData/person PUT Update person
/springData/person/{id} DELETE Delete person by id

Let’s start creating our Rest client project to test these web services. Below image shows our final Spring RestTemplate example project. Spring RestTemplate Example

Spring RestTemplate Maven Dependencies

We need spring-core, spring-context dependencies for spring framework. Then we need spring-web artefact that contains RestTemplate class. We also need jackson-mapper-asl for Spring JSON support through Jackson API.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.journaldev.spring</groupId>
	<artifactId>SpringRestTemplate</artifactId>
	<version>1.0-SNAPSHOT</version>
	<properties>
		<spring.framework>4.3.0.RELEASE</spring.framework>
		<spring.web>3.0.2.RELEASE</spring.web>
		<serializer.version>2.8.1</serializer.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.framework}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.framework}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.web}</version>
		</dependency>
	</dependencies>
</project>

Spring Configuration Class

We have to define a spring bean for RestTemplate class, that’s done in AppConfig class.

package com.journaldev.spring.config;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
@ComponentScan("com.journaldev.spring")
public class AppConfig {

	@Bean
	RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
		converter.setObjectMapper(new ObjectMapper());
		restTemplate.getMessageConverters().add(converter);
		return restTemplate;
	}
}

Note that RestTamplate uses MessageConverter and we need to set this property in the RestTemplate bean. In our example we are using MappingJacksonHttpMessageConverter for fetching data from JSON format.

Model Class

Since we are trying to convert JSON returned by our web service to a java object using jackson mapper, we have to create the model class for this. Note that this model class will be very similar to the model class used in the web service, except that here we don’t need JPA annotations.

package com.journaldev.spring.model;

public class Person {

	private Long id;

	private Integer age;

	private String firstName;

	private String lastName;

	public Person() {
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getFirstName() {
		return firstName;
	}

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

	public String getLastName() {
		return lastName;
	}

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

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

Spring RestTemplate Client Class

Final step is to create the client classes that will use RestTemplate bean defined above.

package com.journaldev.spring.config;

import java.util.List;

import org.springframework.http.HttpStatus;

import com.journaldev.spring.model.Person;

public interface PersonClient {
	List<Person> getAllPerson();

	Person getById(Long id);

	HttpStatus addPerson(Person person);

	void updatePerson(Person person);

	void deletePerson(Long id);
}
package com.journaldev.spring.config;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.journaldev.spring.model.Person;

@Service
public class PersonClientImpl implements PersonClient {

	@Autowired
	RestTemplate restTemplate;

	final String ROOT_URI = "https://localhost:8080/springData/person";

	public List<Person> getAllPerson() {
		ResponseEntity<Person[]> response = restTemplate.getForEntity(ROOT_URI, Person[].class);
		return Arrays.asList(response.getBody());

	}

	public Person getById(Long id) {
		ResponseEntity<Person> response = restTemplate.getForEntity(ROOT_URI + "/"+id, Person.class);
		return response.getBody();
	}

	public HttpStatus addPerson(Person person) {
		ResponseEntity<HttpStatus> response = restTemplate.postForEntity(ROOT_URI, person, HttpStatus.class);
		return response.getBody();
	}

	public void updatePerson(Person person) {
		restTemplate.put(ROOT_URI, person);
	}

	public void deletePerson(Long id) {
		restTemplate.delete(ROOT_URI + id);

	}
}

The code is self understood, we are calling RestTemplate methods based on the URI and the HTTP method and by passing appropriate request object if needed.

Spring RestTemplate Test Class

It’s time to test our Spring RestTemplate example project, below class shows how to use RestTemplate methods in Spring way.

package com.journaldev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.HttpStatus;

import com.journaldev.spring.config.AppConfig;
import com.journaldev.spring.config.PersonClient;
import com.journaldev.spring.model.Person;

public class Main {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

		PersonClient client = applicationContext.getBean(PersonClient.class);

		System.out.println("Getting list of all people:");

		for (Person p : client.getAllPerson()) {
			System.out.println(p);
		}

		System.out.println("\nGetting person with ID 2");

		Person personById = client.getById(2L);

		System.out.println(personById);

		System.out.println("Adding a Person");
		Person p = new Person();
		p.setAge(50);
		p.setFirstName("David");
		p.setLastName("Blain");
		HttpStatus status = client.addPerson(p);
		System.out.println("Add Person Response = " + status);

		applicationContext.close();
	}
}

When I run above program against my local setup, I get following output.

Getting list of all people:
Person{id=2, age=30, firstName='Oksi', lastName=' Bahatskaya'}
Person{id=1, age=30, firstName='Vlad', lastName='Mateo'}

Getting person with ID 2
Person{id=2, age=30, firstName='Oksi', lastName=' Bahatskaya'}
Adding a Person
Add Person Response = 201

Below image shows the web service database table data before and after executing above program. Spring RestTemplate As you can see that the program output matches with the sample table data. That’s all for Spring RestTemplate example, you can download the project from below link.

Download Spring RestTemplate Example Project

Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 29, 2021

Hi pankaj, I need urgent help on as how can we consume existing SOAP service method calls using REST form Request you to please help me or you can share a link for getting to know how Also please let me know how to consume SOAP web service using RestTemplate Thanks, Shreedhar Bhumralkar

- Shreedhar Bhumralkar

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 12, 2018

    Thanks for explanation. Can you suggest best way to make 100-1000 post request to any rest URL. I am worried about connection establishment/closer for each request, although I don’t have to write code for same.

    - rohit verma

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 14, 2018

      How to run this app? I am getting below error: INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2ff4f00f: startup date [Wed Nov 14 10:40:41 IST 2018]; root of context hierarchy Getting list of all people: Exception in thread “main” org.springframework.web.client.ResourceAccessException: I/O error: Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:453) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401) at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:221) at com.journaldev.spring.config.PersonClientImpl.getAllPerson(PersonClientImpl.java:23) at com.journaldev.spring.Main.main(Main.java:19) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source)

      - priyanka

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Get our biweekly newsletter

        Sign up for Infrastructure as a Newsletter.

        Hollie's Hub for Good

        Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

        Become a contributor

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        Welcome to the developer cloud

        DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

        Learn more
        DigitalOcean Cloud Control Panel