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:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
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
):
@Bean
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
:
@Autowired
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.