Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading