Chuleta
Consumir APIs REST
Idea clave
`RestTemplate` y `RestClient` son los clientes HTTP síncronos de Spring: construyen la petición, convierten objetos a JSON y viceversa con los mismos `HttpMessageConverter` de Spring MVC y traducen los estados 4xx/5xx en excepciones. `RestTemplate` usa métodos con nombre por operación; `RestClient` (Spring 6.1+) una API fluida.
Diagrama (UML)
classDiagram
direction LR
class WodClient {
<<@Component>>
-rest: RestClient
+today() Wod
+byName(String) Wod
}
class LegacyWodClient {
<<@Component>>
-rest: RestTemplate
+today() Wod
+publish(Wod) URI
}
class RestTemplate {
<<template>>
+getForObject(url, Class, vars) T
+getForEntity(url, Class, vars) ResponseEntity
+postForLocation(url, body) URI
+put(url, body, vars)
+delete(url, vars)
+exchange(url, method, entity, type) ResponseEntity
}
class RestClient {
<<fluent>>
+get() / post() / put() / delete()
+uri(...) retrieve() body(T)
}
class RestClientResponseException {
<<unchecked>>
}
WodClient --> RestClient
LegacyWodClient --> RestTemplate
RestTemplate ..> HttpMessageConverter
RestClient ..> HttpMessageConverter
RestClientResponseException <|-- HttpClientErrorException : 4xx
RestClientResponseException <|-- HttpServerErrorException : 5xxPiezas clave
RestTemplate:getForObject,getForEntity,postForObject,postForEntity,postForLocation,put,delete,exchange,executeRestClient:get()/post()/put()/delete()→.uri(...)→.retrieve()→.body(T)/.toEntity(T)/.toBodilessEntity()ParameterizedTypeReference<List<Wod>>: tipos genéricos en la respuestaHttpClientErrorException(4xx),HttpServerErrorException(5xx), ambasRestClientResponseExceptionRestTemplateBuilderyRestClient.Builder: los construye Spring Boot ya configurados@RestClientTest+MockRestServiceServer: probar el cliente sin red
WodClient.java
public Wod today() {
return rest.get()
.uri("/wods/today")
.accept(MediaType.APPLICATION_JSON)
.retrieve() // send it and look at the response
.body(Wod.class); // JSON → Wod (4xx/5xx → RestClientResponseException)
}
public List<Wod> history() {
return rest.get().uri("/wods").retrieve()
.body(new ParameterizedTypeReference<List<Wod>>() { });
}
public URI publish(Wod wod) {
return rest.post().uri("/wods")
.contentType(MediaType.APPLICATION_JSON)
.body(wod) // Wod → JSON
.retrieve()
.toBodilessEntity()
.getHeaders().getLocation();
}Recuerda para el examen
getForObjectdevuelve solo el cuerpo;getForEntity, unResponseEntitycon estado y cabeceraspostForLocationdevuelve la cabeceraLocation(unaURI)exchangees el método general: verbo,HttpEntity(cuerpo y cabeceras) y tipo de respuesta- Las variables de plantilla (
/wods/{name}) se rellenan con los argumentos extra o unMap RestTemplateestá en modo mantenimiento: no se elimina, pero lo nuevo esRestClient(síncrono) oWebClient(reactivo)- Inyecta el builder de Spring Boot, no hagas
new RestTemplate(): así heredas conversores, timeouts y personalizaciones
Trampas de examen
- Con
RestTemplate, un 404 lanzaHttpClientErrorException.NotFound; no devuelvenull - Para
List<Wod>hace faltaParameterizedTypeReference(o un arrayWod[]);List.classpierde el tipo genérico putydeletedeRestTemplatedevuelvenvoid; para leer la respuesta usaexchange- Con
rootUri/baseUrl, las expectativas deMockRestServiceServerusan la ruta relativa