How to call third party API using spring rest template
When we create an application, of course we need a third-party service or API such as the google API, facebook API, twitter API and others to support the application or business processes in the application. Spring boot already provides classes to integrate APIs from third parties, namely using rest templates. And this time we will try to integrate third party APIs using springboot rest template.
In this article we make simple Rest API and integration data USA population API.
Article Content:
- Initiate the spring boot project
- Add the required jar / dependencies to the spring boot project
- Configuration for Spring
- Create service
- Create controller
- Test
Technology
- Java 11
- Spring Boot
- Maven
1.Initiate the spring boot project
To Create spring boot project, Open the Spring initializr https://start.spring.io.
2.Add the required jar / dependencies to the spring boot project
Add Dependencies for Spring Boot in pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3.Configuration for Spring
Add Configuration in application.properties
server.name=springboot-rest-template
server.port=8081
url.usa.population = https://datausa.io/api/data?drilldowns=Nation&measures=Population
add rest template class into main application.
package id.co.lemoncode21.resttemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
4.Create service
service/GovernmentService.java
In this file we add two functions. one as an example to retrieve data by GET method and second as an example if our service needs to POST, UPDATE, DELETE methods to a third party service.
package id.co.lemoncode21.resttemplate.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class GovernmentService {
@Autowired
private RestTemplate restTemplate;
@Value("${url.usa.population}")
private String url;
// example get API
public Object getAllData() {
try {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCEPT, "application/json");
headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<Object>() {});
return response.getBody();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// example POST DELETE UPDATE API
public Object postAPI(Object request) {
try {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCEPT, "application/json");
headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
// headers.add(HttpHeaders.AUTHORIZATION, token); add some token if API need Token
HttpEntity entity = new HttpEntity(request, headers);
// Change Object to object class according to response API
// example
// ResponseEntity<Person> response = restTemplate.exchange(url, HttpMethod.POST, entity, new ParameterizedTypeReference<Person>()});
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.POST, entity, new ParameterizedTypeReference<Object>() {});
return response.getBody();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
5.Create controller
Controller is a REST Controller which has request mapping methods for RESTful requests.
controller/BaseController.java
package id.co.lemoncode21.resttemplate.controller;
import id.co.lemoncode21.resttemplate.services.GovernmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BaseController {
@Autowired
private GovernmentService governmentService;
@GetMapping("/")
public String Home() {
return "Helo Home";
}
@GetMapping("/getAll")
public Object getAll() {
try {
return this.governmentService.getAllData();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
6.Test
Call home API via postman
Call Get All API via postman
Conclusion
In this article we make a simple project how to call third party api with spring boot. you can see code in github.