Skip to content

Chiamate API con RestTemplate

Michele Perlotto edited this page Nov 19, 2025 · 1 revision

RestTemplate è una classe sincrona di Spring che semplifica la creazione e invio di chiamate HTTP a servizi REST. Per utilizzare RestTemplate è consigliato definirlo come @Bean (ad esempio all'interno di una classe @Config), per essere istanziato e passato dove necessario automaticamente da Spring.

@Configuration
public class RestTemplateConfig {
    
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Metodo exchange()

Il metodo exchange() è il metodo più flessibile che RestTemplate mette a disposizione per effettuare chiamate HTTP. Permette di specificare:

  • L'url dell'endpoint di destinazione;
  • Il metodo HTTP;
  • Header e corpo della richiesta;
  • Il tipo di risposta atteso (modellabile tramite DTO, ad esempio);
  • I valori da sostituire ai placeholder nell'url, se presenti.
public <T> ResponseEntity<T> exchange(
    String url,
    HttpMethod method,
    HttpEntity<?> requestEntity,
    Class<T> responseType,
    Object... uriVariables
) throws RestClientException

Esempi pratici

GET con headers custom

public User getUserWithAuth(Long id, String token) {
    String url = "https://api.example.com/users/{id}";
    
    // Aggiungo l'autenticazione tramite token all'header
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + token);
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    // Costruisco la richiesta
    HttpEntity<Void> requestEntity = new HttpEntity<>(headers);
    
    ResponseEntity<User> response = restTemplate.exchange(
        url,
        HttpMethod.GET,
        requestEntity,
        User.class,
        id
    );
    
    return response.getBody();
}

POST con request body

public User createUser(User newUser) {
    String url = "https://api.example.com/users";
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    // Aggiungo il corpo della richiesta 
    HttpEntity<User> requestEntity = new HttpEntity<>(newUser, headers);
    
    ResponseEntity<User> response = restTemplate.exchange(
        url,
        HttpMethod.POST,
        requestEntity,
        User.class
    );
    
    return response.getBody();
}

GET per ricevere collezioni di dati

public List<User> getAllUsers() {
    String url = "https://api.example.com/users";
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    HttpEntity<Void> requestEntity = new HttpEntity<>(headers);
    
    ResponseEntity<List<User>> response = restTemplate.exchange(
        url,
        HttpMethod.GET,
        requestEntity,
        new ParameterizedTypeReference<List<User>>() {}
    );
    
    return response.getBody();
}

Se il tipo di risposta restituito dall'API è una collezione, è necessario usare ParameterizedTypeReference per il tipo della risposta.

Gestione custom degli errori

public User getUserSafe(Long id) {
    String url = "https://api.example.com/users/{id}";
    
    try {
        ResponseEntity<User> response = restTemplate.exchange(
            url,
            HttpMethod.GET,
            null,
            User.class,
            id
        );
        
        return response.getBody();
    } catch (HttpClientErrorException e) {
        // Gestione errori 4xx
    } catch (HttpServerErrorException e) {
        // Gestione errori 5xx
    } catch (RestClientException e) {
        // Gestione altri errori
    }
}

Clone this wiki locally