Spring RestTemplate - consume paginated response API java


RestTemplate in spring used to consume REST API’s with simplifying the process. It includes http connection handling and integrated with jackson binder to serialize and deserilize java object to/from json object. It is very easy to integrate external API’s in Java and Android codebases.

This tutorial will not cover creating REST API in java

RESTtemplate consume plain json data

Let’s assume that REST API returns following json data

The following data returns only array, but not pagination data.

[{"id":1,"mobile":"1234","email":test@gmail,"designation":"Manager","department":"Finance "}]

Let’s create java value object class for storing data from REST API’s

public class EmployeeInfo {
    private String id;
    private String mobile;
    private String designation;
    private String department;
    private String email;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getId() {
        return id;
    }

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

And the REST API consume with plan

final String url = "REST API URL";
RestTemplate restTemplate = new RestTemplate();
EmployeeInfo emp = restTemplate.getForObject(url, EmployeeInfo.class);

restTemplate in Spring framework object do the following things

  • It creates and manages HTTP connection manager for URL
  • It uses Jackson library for serialize and deserialize the java object from JSOn data
  • getForObject accepts url and Object class and return the response in java object

This is way how Resttemplate simplified java object converted from JSON.

How to consume paginated response with resttemplate in spring

pagination is a logic in which returns few records when there are more records

for suppose, if API returns the following JSOn response.

{"content":[{"id":1,"mobile":"1234","email":test@gmail,"designation":"Manager","department":"Finance "}],"last":true,"totalElements":1,"totalPages":1,"sort":[],"numberOfElements":1,"first":true,"size":20,"number":0,"empty":false}

API returns pageable data that has following attributes

  • content attribute holds actual data returned from API
  • last true means last page
  • size number of records to return in single call
  • totalPages - returns the total pages of all records
  • sort - will give sorting is enabled on any properties
  • first - first page or not

If API returns these json data, We have to customization to handle this pageable response

First lets create PaginatedResponse.java which extends PageImpl from spring framework


import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;

public class PaginatedResponse<T> extends PageImpl<T> {
    @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
    public PaginatedResponse(@JsonProperty("content") List<T> content,
                            @JsonProperty("number") int number,
                            @JsonProperty("size") int size,
                            @JsonProperty("totalElements") Long totalElements,
                            @JsonProperty("pageable") JsonNode pageable,
                            @JsonProperty("last") boolean last,
                            @JsonProperty("totalPages") int totalPages,
                            @JsonProperty("sort") JsonNode sort,
                            @JsonProperty("first") boolean first,
                            @JsonProperty("first") boolean first,
                            @JsonProperty("empty") boolean empty) {

        super(content, PageRequest.of(number, size), totalElements);
    }

    public PaginatedResponse(List<T> content, Pageable pageable, long total) {
        super(content, pageable, total);
    }

    public PaginatedResponse(List<T> content) {
        super(content);
    }

    public PaginatedResponse() {
        super(new ArrayList<>());
    }
}

In consuming API, the code as follows

We have to use ParameterizedTypeReference provides an type reference to jackson object wrapper to convert the PaginatedResponse with format for Employee class

ParameterizedTypeReference<PaginatedResponse<Employee>> responseType = new ParameterizedTypeReference<PaginatedResponse<Employee>>() { };

ResponseEntity<RestResponsePage<Employee>> result = restTemplate.exchange(url, HttpMethod.GET, null/, responseType);

List<Employee> employeeList = result.getBody().getContent();

Conclusion

Consuming REST API with plan object is easy and strightforward,But paginated response format needs to play with spring classes to return correct format.

For any reason, if returned response is different from above, You have to modify accorndingly.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.