How to consume an external API in Spring Boot

Asked

Viewed 12,870 times

6

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

2 answers

9


You can use the Resttemplate for this.

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

Thus, we would have to create a class in Java to receive these values, respecting the same Json format that you 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 quite 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 a POST 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 )
  • 2

    this solution is much simpler hehe

5

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 - Create a Resttemplate instance 2 - The URL you want to access 3 - The call itself. Since in this example we are not concerned with mapping the Response to an object, we define that we will save this Response to a String.

Now, suppose you want to map the direct sponse to an object, setting in it the values:

1- The class that will be populated with Sponse:

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

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

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

Source: Resttemplate

  • 2

    vaaaaleeeu, that’s what I wanted kkkk Brigadão

Browser other questions tagged

You are not signed in. Login or sign up in order to post.