How to access third party API data in Java Spring Boot

I would like to ask how can I access the fields in json ("latitude", "latitude") to be able to display them as string in the browser.

@RestController
@RequestMapping("/api/v1/")
public class ISSTrackerController {

    @GetMapping("/location")
    public ResponseEntity<String> getISSLocation() {
        String uri = "http://api.open-notify.org/iss-now.json";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(uri, String.class);

        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}

>Solution :

To get the data from the response in java, you will need to create some POJOs to get the response:

class IssPosition {
    private Double latitude;
    private Double longitude;

    // getters & setters
}

class IssResponse {
    // Here the iss_position property in hte response is in cammel case,
    // with the @JsonProperty annotation we tell the parser to pass that 
    // property to the annotated field issPosition
    @JsonProperty("iss_position")
    private IssPosition issPosition;
    private String message;
    private Timestamp timestamp;

    // getters & setters
}

Then you can make your call with RestTemplate

@RestController
@RequestMapping("/api/v1/")
public class ISSTrackerController {

    @GetMapping("/location")
    public ResponseEntity<String> getISSLocation() {
        String uri = "http://api.open-notify.org/iss-now.json";
        RestTemplate restTemplate = new RestTemplate();
        // We get te response as an IssResponse object
        IssResponse result = restTemplate.getForObject(uri, IssResponse.class);
        // We get the iss_position property so you have access 
        // to the latitude and longitude fields by
        IssPosition position = result.getIssPosition();
        // You can just return the position so you have a json like this one: 
        // { "latitude": "-24.0470", "longitude": "64.0261" }
        return new ResponseEntity<>(position, HttpStatus.OK);
    }
}

Leave a Reply