Last active
June 23, 2025 13:39
-
-
Save deepanshumehtaa/200086ffaacbd3da8e61b615a929c729 to your computer and use it in GitHub Desktop.
Java Rest Template.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper --> | |
<dependency> | |
<groupId>org.modelmapper</groupId> | |
<artifactId>modelmapper</artifactId> | |
<version>3.2.2</version> | |
</dependency> | |
....................................................................................................... | |
package com.example.DemoApp.service; | |
import com.example.DemoApp.Dtos.BirdDTO; | |
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.JsonMappingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import org.modelmapper.ModelMapper; | |
import org.springframework.web.util.UriComponentsBuilder; | |
import java.util.*; | |
import org.springframework.http.*; | |
import org.springframework.stereotype.Service; | |
import org.springframework.web.client.RestClientException; | |
import org.springframework.web.client.RestTemplate; | |
import java.util.List; | |
import lombok.ToString; | |
@Service | |
public class RestTemplateBird { | |
// final static String url = "https://www.freetestapi.com/api/v1/birds"; | |
final static String birdURL = "http://127.0.0.1:8000/dummy/birds?count=100"; | |
final static String postURL = "http://127.0.0.1:8000/dummy/post_it_1/"; | |
RestTemplate restTemplate = new RestTemplate(); | |
public List<BirdDTO> callAPIV1() { | |
List<BirdDTO> birdsDTOList = new ArrayList<>(); | |
try { | |
// can't use here because response is list of map | |
// ResponseEntity<BirdDTO> response = restTemplate.getForEntity(url, BirdDTO.class); | |
ResponseEntity<String> response = restTemplate.getForEntity(birdURL, String.class); | |
if (response.getStatusCode().is2xxSuccessful()) { | |
String jsonStr = response.getBody(); | |
ObjectMapper objectMapper = new ObjectMapper(); | |
List<Map<String, Object>> mapList = objectMapper.readValue(jsonStr, List.class); | |
for (Map<String, Object> mapBird : mapList) { | |
BirdDTO birdDTO = new BirdDTO(); | |
ModelMapper modelMapper = new ModelMapper(); | |
BirdDTO birdObj = modelMapper.map(mapBird, BirdDTO.class); // Assuming 'age' is an Integer | |
birdsDTOList.add(birdObj); | |
} | |
return birdsDTOList; | |
} else { | |
System.out.println("Failed to retrieve data"); | |
return birdsDTOList; | |
} | |
} catch (RestClientException e) { | |
System.out.println("Error calling API: " + e.getMessage()); | |
} catch (JsonMappingException e) { | |
throw new RuntimeException(e); | |
} catch (JsonProcessingException e) { | |
throw new RuntimeException(e); | |
} | |
return null; | |
} | |
public List<Map<String, Object>> callAPIV2() throws JsonProcessingException { | |
HttpHeaders headers = new HttpHeaders(); | |
headers.add("trace-id", "some-trace-id"); | |
headers.setContentType(MediaType.APPLICATION_JSON); | |
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(headers); | |
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(birdURL) | |
.queryParam("count", 2); | |
ResponseEntity<String> response = restTemplate.exchange( | |
uriBuilder.toUriString(), | |
HttpMethod.GET, | |
requestEntity, | |
String.class | |
); | |
if (response.getStatusCode() == HttpStatus.OK) { | |
String jsonStr = response.getBody(); | |
ObjectMapper OMapper = new ObjectMapper(); | |
List<Map<String, Object>> mapList = OMapper.readValue(jsonStr, List.class); | |
return mapList; | |
} else { | |
System.out.println("Error in Calling the API"); | |
return null; | |
} | |
} | |
public Map<String, Object> callPOSTAPIV1(Map<String, Object> reqBody) throws JsonProcessingException { | |
HttpHeaders headers = new HttpHeaders(); | |
headers.add("trace_id", "some-trace-id"); | |
headers.setContentType(MediaType.APPLICATION_JSON); | |
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(reqBody, headers); | |
ResponseEntity<String> response = restTemplate.exchange( | |
postURL, | |
HttpMethod.POST, | |
requestEntity, | |
String.class | |
); | |
if (response.getStatusCode() == HttpStatus.OK) { | |
String jsonStr = response.getBody(); | |
ObjectMapper OMapper = new ObjectMapper(); | |
Map<String, Object> inReturnResponse = OMapper.readValue(jsonStr, Map.class); | |
return inReturnResponse; | |
} else { | |
System.out.println("Error in Calling the API"); | |
return null; | |
} | |
} | |
public SuccessResponse callGETSuccess() throws JsonProcessingException { | |
HttpHeaders headers = new HttpHeaders(); | |
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(headers); | |
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(birdURL) | |
.queryParam("count", 2); | |
ResponseEntity<SuccessResponse> response = restTemplate.exchange( | |
uriBuilder.toUriString(), | |
HttpMethod.GET, | |
requestEntity, | |
SuccessResponse.class | |
); | |
if (response.getStatusCode() == HttpStatus.OK) { | |
SuccessResponse jsonStr = response.getBody(); | |
return jsonStr; | |
} else { | |
System.out.println("Error in Calling the API"); | |
return null; | |
} | |
} | |
} | |
.............................DTO (Data Transfer Object) very much like @dataclass in python........................................ | |
package com.example.DemoApp.Dtos; | |
import com.fasterxml.jackson.annotation.JsonProperty; | |
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
import lombok.ToString; | |
@Data | |
@NoArgsConstructor | |
@AllArgsConstructor | |
@ToString | |
public class BirdDTO { | |
private int id; | |
private String name; | |
private String species; | |
private String family; | |
private String habitat; | |
@JsonProperty("place_of_found") | |
private String placeOfFound; | |
private String diet; | |
private String description; | |
@JsonProperty("wingspan_cm") | |
private int wingspanCm; | |
private double weightKg; | |
private String image; | |
} | |
@Data | |
@AllArgsConstructor | |
public class SuccessResponse { | |
private boolean success; | |
private ArrayList<Object> data; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment