Kevin
Kevin

Reputation: 15

Spring Boot to return JSON String from an external API

I have a simple Spring boot project that uses controller mappings to get hard coded information from a class in my project.

For example, if I run the request : localhost:8080/topics, A JSON response is returned with the list of Topic Objects that i have previously created

I want to take this one step further and have a class who's variables are populated by calling this API and parsing the response :
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo

I believe this can be done in Java by creating a HTTP connection and reading the data from an input stream, but is the an easier way of doing this with spring boot? Im not fully sure of the name of this procedure hence Im having trouble finding solutions online

Upvotes: 0

Views: 9896

Answers (2)

derickson82
derickson82

Reputation: 496

Since you are using Spring Boot, making use of Spring's RestTemplate makes sense. It comes with several message converters out of the box, and uses Jackson by default for json content.

Spring has published a good Getting Started page for consuming RESTful web services.

However, the json content returned by that services doesn't look like it will map well to a Java object, so you may have to deserialize it to a HashMap to get to the data you want.

Upvotes: 2

StanislavL
StanislavL

Reputation: 57381

I did an attempt to create something like this.

https://github.com/StanislavLapitsky/SpringSOAProxy

The idea is to register controller interfaces. Each of the interfaces are mapped to some URL. For the interfaces a dynamic proxy are generated (if the implementations are not available locally). So developer just call controller's interface method. The method is invoked for dynamically generated proxy. The proxy uses RestTemplate to call remote URL. It sends and receive JSON and deserializes the returned JSOn to POJO objects returned from the controller.

You need to declare contract - controller interfaces plus DTO to exchange data as well as mapping to understand which URL should be called for each controller.

Upvotes: 0

Related Questions