How to consume an external API in Spring Boot

4

I have a springboot application that needs to extract information from another application. How do I make this communication and can I extract this data?

    
asked by anonymous 09.05.2018 / 13:37

2 answers

6

You can use RestTemplate for this.

As an example, imagine that you want to make a GET for the system at address www.sistema.com/api/ on the% identifier% service equal to pedidos . You will receive a Json with the attributes 10 and nome of this request.

So, we would have to create a class in Java to receive these values, respecting the same Json format that it will receive. So we can create the following class:

class Pedido {
    private String nome;
    private BigDecimal valor;
    //gets e sets
}

And to call the service, it's pretty simple:

RestTemplate restTemplate = new RestTemplate();
Pedido pedido = restTemplate.getForObject("http://www.sistema.com/api/pedidos/10", Pedido.class);

RestTemplate is very flexible, the above example is very basic. If you want to do something more elaborate, like valor passing some Http Headers, we can have this scenario :

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("nome", "João Silva");
map.add("valor", new BigDecimal("1.00"));

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<Pedido> response = restTemplate.postForEntity( url, request , Pedido.class )
    
09.05.2018 / 13:47
3

You need a Spring class called RestTemplate . A very simple example of a get:

RestTemplate restTemplate = new RestTemplate(); //1
String url = "http://www.algumacoisa.com.br/api"; //2
ResponseEntity<String> response
  = restTemplate.getForEntity(url, String.class); //3

1 - Creates an instance of RestTemplate 2 - The URL you want to access 3 - The call itself. As this example is not concerned with mapping the response to an object, we have defined that we will store this response in a String itself.

Now, assuming you want to map the direct response to an object, setting the values in it:

1- The class that will be populated with the response:

public class Foo implements Serializable {
    private long id;
 
    private String nome;
    //getters e setters
}

2- The method that will consume api. Note that the method used is getForObject()

Foo foo = restTemplate
  .getForObject(fooResourceUrl, Foo.class);

Source: RestTemplate

    
09.05.2018 / 13:58