spring-boot Consuming a REST API with RestTemplate (GET)


To consume a REST API with RestTemplate, create a Spring boot project with the Spring boot initialzr and make sure the Web dependency is added:


Once you've set up your project, create a RestTemplate bean. You can do this within the main class that has already been generated, or within a separate configuration class (a class annotated with @Configuration):

public RestTemplate restTemplate() {
    return new RestTemplate();

After that, create a domain class, similar to how you should do when creating a REST service.

public class User {
    private Long id;
    private String username;
    private String firstname;
    private String lastname;

    public Long getId() {
        return id;

    public String getUsername() {
        return username;

    public void setUsername(String username) {
        this.username = username;

    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;

In your client, autowire the RestTemplate:

private RestTemplate restTemplate;

To consume a REST API that is returning a single user, you can now use:

String url = "http://example.org/path/to/api";
User response = restTemplate.getForObject(url, User.class);

Consuming a REST API that is returning a list or array of users, you have two options. Either consume it as an array:

String url = "http://example.org/path/to/api";
User[] response = restTemplate.getForObject(url, User[].class);

Or consume it using the ParameterizedTypeReference:

String url = "http://example.org/path/to/api";
ResponseEntity<List<User>> response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {});
List<User> data = response.getBody();

Be aware, when using ParameterizedTypeReference, you'll have to use the more advanced RestTemplate.exchange() method and you'll have to create a subclass of it. In the example above, an anonymous class is used.