Skip to content

Instantly share code, notes, and snippets.

@willyanmarques
Created July 24, 2019 22:33
Show Gist options
  • Save willyanmarques/548c25e1bfb34060154652fa52589531 to your computer and use it in GitHub Desktop.
Save willyanmarques/548c25e1bfb34060154652fa52589531 to your computer and use it in GitHub Desktop.
public class REST {
private static List<Contact> listaContatos = new List<Contact>(); //Lista vazia, vamos inserir os contatos nela dentro do loop "for"
public static void calloutAPI(){
try{
RestModel wrapper = new RestModel();
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://reqres.in/api/users?page=1');
req.setMethod('GET');
HttpResponse res = http.send(req);
if(res.getStatusCode() == 200){
wrapper = (RestModel) JSON.deserialize(res.getBody(), RestModel.Class);
for(DataModel d: wrapper.data){`
//Adiciono dinamicamente a cada iteracao um novo contato na lista
listaContatos.add(new Contact(FirstName = d.first_name, LastName = d.last_name, Email = d.email));
}
} else {
System.debug('Falha ao obter dados da API. Status code: ' + res.getStatusCode());
}
//Verifico o tamanho da lista e realizo a DML
if(listaContatos.size() > 0){
insert listaContatos;
}
}
catch(Exception e){
System.debug('Exception! Mensagem: ' + e.getMessage() + ' Linha: ' + e.getLineNumber());
}
}
//Classes wrapper
public class RestModel {
public List<DataModel> data = new List<DataModel>();
}
//Modelo do objeto que vamos receber na lista JSON
public class DataModel {
public Integer id;
public String email;
public String first_name;
public String last_name;
public String avatar;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment