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

AJAX - How To Retrieve JSON Response from PHP script

Hello Friends, This is my first tutorial post. Today I'll explain you how to retrieve JSON response via Ajax call. First we build a PHP script to send response in JSON format, then we will gather this response from an Ajax call through jQuery script. Let’s first create a PHP script  Create a PHP script, I’ll name it as “json_response.php” And add following code in it json_response.php <?php //set header for JSON response header("Content-Type: application/json"); //render array in JSON format echo json_encode(array('status' => 200, 'message' => 'Response from PHP script in JSON format.')); This is a basic example to send JSON response. PHP script will send response with status code and message. Now create a HTML file to fetch JSON response and add it in header tag. Create a HTML file, I’ll name it as “json_response.html” And add following code. json_response.html <html>           ...

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

Twig Tutorials: Install and Configure

In this tutorial, we'll look at how to install Twig within your PHP project and thereafter configure it so that we can create and use a Twig template inside our PHP web application. Later on, we'll see a simple Twig template example that displays a "Welcome to Twig template" message. Let's take it one step at a time. Install The Twig template can be installed using Composer, Git, or PEAR. In this tutorial, we will use Composer to install Twig. To do so, we'll need to make a "composer.json" file. { "require" : { "twig/twig" : "1.*" } } From the console, run the following command . $ php composer.phar install This command will install Twig library. Configuration To use the Twig template, we should first configure it. To achieve this, we will write an index.php file which will configure the Twig autoloader and generate the Twig environment. We will render the Twig temp...