Saturday, 3 March 2018

How to make API calls using RestTemplate ?


Using RestTemplate
  • Create a service / facade class to call the API.
  • Inject new bean of RestTemplate (A Spring class) in this class using @Bean annotation.
  • Call methods : getForObject, postForObject (Best one is to use exchange method)
Below example uses a global API available on internet for getting data.


@Component
public class EmployeeService {
    @Resource
    private RestTemplate restTemplate;


    private String baseUrl = "https://jsonplaceholder.typicode.com/";
   
    @Bean
    RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
   
    public User getApiUsers() {
        User user = restTemplate.getForObject(baseUrl + "users/1", User.class);
        return user;
    }
}



Create required POJOs to hold data models
public class User {
    private Long id;
    private String name;
    private String username;
    private String email;


    // getters and setters
    // toString
}


Create Controller to inject and call the service to get API data
Used @RestController to expose API and provide request mapping
@RestController
@RequestMapping("emp")

public class EmpController {
    @Resource
    private EmployeeService employeeService;
   
    @GetMapping
    public User getUsers() {
        User user = employeeService.getApiUsers();
        System.out.println("USER : " + user);
        return user;
    }
}


No comments:

Post a Comment

Note: only a member of this blog may post a comment.