Skip to main content

Spring Boot RestTemplate Guide with Example


What is RestTemplet?

RestTemplate is a HTTP Client library that provides basic APIs for executing different HTTP type requests.

RestTemplate is one of the HTTP libraries available on the market.

The Spring Boot team designed and maintains it.

As previously said, it is a client library, which means it may be utilised in our application as a stand-alone dependency. To utilise it, you don't require a complete Spring boot application.

It's suitable for use in simple Java applications as well as other frameworks such as Micronaut, Play and others.


Setup

Add RestTemplate dependency to project, for this tutorial I am creating a simple java application to consume HTTP request and a node application to provide HTTP service.

For Gradle build tool

Add the following dependency in the build.gradle file.

// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.6.3'

This will provide classes to create instance of RestTemplate.

RestTemplate restTemplate = new RestTemplate();

REST APIs

Node.js has a useful library that converts a json file to a RESTful service.

Install the npm library as

$ npm install json-server --save-dev

Now define the JSON structure for the HTTP service.

create db.json file and add following snippet

{
  "projects": [
    {
      "id" :  1, 
      "name" :  "RestTemplate", 
      "description" :  "Project to demonstrate workflow of RestTemplate"
    }]
}

Now, run server as

$ node_modules/.bin/json-server db.json 

Note:  Use following command to find location of  node_module executable
npm bin 

Model

Define any POJO class which is use to exchange the request and response.

public class ProjectModel {
    private Integer id;
    private String name;
    private String description;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "{id: " + id + ", name: " + name + ", description: " + description + "}";
    }
}


HTTP Get Request

Use following snippet to get single records.

// Instantiate RestTemplate
RestTemplate restTemplate = new RestTemplate();

String apiEndpoint = "http://localhost:3000/projects";

// HTTP GET single record
ResponseEntity<ProjectModel> entity = restTemplate.getForEntity(apiEndpoint + "/1", ProjectModel.class);
ProjectModel record = entity.getBody();
System.out.println("Fetch single records");
System.out.println(record);

First we defined restTemplate instance and endpoint to establish HTTP communication.

getForEntity method will fetch the resource and convert it into an appropriate Java class. Here, it is a ProjectModel class.


Use following snippet to fetch all records.

// HTTP GET all records
System.out.println("Fetch all records");
ResponseEntity<List> records = restTemplate.getForEntity(apiEndpoint, List.class);
records.getBody().forEach(System.out::println);

This will create a list of Java objects. One thing to notice here is that the result is a list of Java objects.
It is necessary to iterate the list and cast each object in order to convert it into a project model.

The Spring framework provides a handy technique to cast a list of objects to avoid this complexity.

// HTTP GET all with casting of entity
ParameterizedTypeReference<List<ProjectModel>> typeReference = new ParameterizedTypeReference<List<ProjectModel>>() {
};

ResponseEntity<List<ProjectModel>> responseEntity = restTemplate.exchange(apiEndpoint, HttpMethod.GET, null, typeReference);
List<ProjectModel> projectModels = responseEntity.getBody();

projectModels.forEach(System.out::println);


HTTP POST Request

 //HTTP POST Request
ProjectModel projectModel = new ProjectModel();
projectModel.setName("Blogger App");
projectModel.setDescription("Blog application to publish blogpost");

ResponseEntity<ProjectModel> response = restTemplate.postForEntity(apiEndpoint, projectModel, ProjectModel.class);
System.out.println(response.getBody());

The postForEntity function takes three arguments, API endpoint, the other payload and its class type.

Here we have not set the id of the ProjectModel. It should be created by the server and you should get it from the response object.


HTTP PUT Request

 //HTTP PUT request
projectModel = response.getBody();
projectModel.setName("Blog post app");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<ProjectModel> requestEntity = new HttpEntity<ProjectModel>(projectModel, httpHeaders);
response = restTemplate.exchange(apiEndpoint + "/" + projectModel.getId(), HttpMethod.PUT, requestEntity, ProjectModel.class);

System.out.println("PUT response");
System.out.println(response.getBody()); 

The above example shows another way to communicate with an API server.

The exchange method requires HttpEntity to pass request information to the server, and it also includes HTTP header information. 

HTTP Delete Request

// HTTP Delete request
restTemplate.delete(apiEndpoint + "/" + projectModel.getId());
        

There is no return type for this method, and even if you use the exchange method to perform an HTTP DELETE, you will get an empty response object.


Conclusion

We went over the basic HTTP Verbs in this post and used RestTemplate to compose requests using all of them.

All of these examples and code snippets were implemented and can be found on GitHub.



Comments

Subscribe for latest tutorial updates

* indicates required

Popular posts from this blog

How to enable SQL logs in Spring Boot application?

This tutorial will demonstrate how to enable and disable SQL log statements in a Spring Boot application in order to debug SQL flow. Problem You will frequently need to debug the SQL statement while developing a Spring Boot application with a SQL database. SQL debug logs can assist you figure out what's wrong with JPA statements and whether or not there's a problem with database connectivity. Example  If you've built custom Spring data JPA methods and need to know what SQL statement is being utilized behind them, return repository . findByUsernameIn ( usernames ); Then you can enable Hibernet debug mode to log SQL statements. Solution Update the application.yml file with the Hibernet configuration as logging: level: org: hibernate: DEBUG or application.properties as logging.level.org.hibernate=DEBUG The SQL statement will appear in the application logs after modifying the configuration file and restarting the application. 2022-04-07 08:41...

Preload Images Using Javascript

Preload Image is technique which helps browser to render images with minimum delay. Today we will see example of image gallery. Gallery contain 5 images which load images one after another whenever user clicks next and back button. This is a basic image gallery scenario which is used in all possible website, then why we need preloaded images for this gallery? Now a day’s most of website becoming faster and user expectation is increasing. Suppose your website doesn’t use preload image technique for gallery and a user visits any image gallery from Google Plus or Facebook and visits your website gallery. Then that user always prefer those websites rather than yours. Why? Because your website load one image at a time. When user click on next button, then only gallery load image and user has wait till it get loaded. To avoid this situation gallery needs to download all images ...

JSON Tutorials : Getting Started

JSON is widely accepted text formatted structured data. JSON stands for " JavaScript Object Notation ". In general JSON can represent 1. Object of database record. 2. Object to represent a list of HTML elements. 3. Result of search query. 4. Response of an Ajax call. Here you can see JSON is used in many different areas and for many different scenarios. This means it has simple data structure. most of programming languages adopt it and it can flow easily from one connection to another. You can find JSON office definition here JSON Official Site . JSON is represented by two structural types, which includes two primitive types. Structural types Array : A sequential list of primitive data types between square brackets [ ] Object : Collection of key, value pair stored inside curly braces { }, where value would be primitive data type Primitive types : There are two primitive types key and value. " key " should be string and " value (data type)...