
Json – messaging format, often used in REST / SOAP web service. There are many public API RESTFul services in the network. Let’s try to get the message in Json format and parse it.
Exercise:
Openexchangerates is open RESTFul web services, get the message, parse and save into database. For example use the service, which returns currency quotes against the US dollar. Let’s see which country in 18 years stood as firmly as possible against the US dollar. Well, how much has Russia gone ‘up’ at the rate of the US dollar.
Used:
Jackson | Json | API RESTFull |
Необходимо выполнить:
– Create database;
– Create REST client;
– Prepare test data;
– Create by loop, fill URL link from txt file;
– Save into db;
Link to API Introduction REST web service.
Get request: /api/historical/2001-02-16.json?app_id=YOUR_APP_ID
We want to get data for each month for the last 18 years.
Need to loop through the parameter: date.
In response, the service returns a message in Json format. Create POJO class.
{ "disclaimer": "Usage subject to terms: https://openexchangerates.org/terms", "license": "https://openexchangerates.org/license", "timestamp": 982342800, "base": "USD", "rates": { "AED": 3.67246, "ALL": 144.529793, "ANG": 1.79, "ARS": 1.000567 } } |
Full script data on GitHub.
CREATE TABLE exchangerates( id serial PRIMARY KEY, data_cur DATA UNIQUE NOT NULL, TIMESTAMP INT, AED DECIMAL, ANG DECIMAL); |
I use libraries to describe POJO lombok and jackson 2
@Getter @Setter @ToString public class ClassRates { private String disclaimer; private String license; private int timestamp; private String base; private Rates rates; } @Getter @Setter @ToString public class Rates{ @JsonView private double AED; @JsonView private double ALL; @JsonView ................... |
For saving data use Spring Jdbc and NamedParameterJdbcTemplate.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.postgresql.Driver"> <property name="url" value="jdbc:postgresql://localhost:5432/gotoqa"> <property name="username" value="postgres"> <property name="password" value="postgres"> </property></property></property></property></bean> |
Call REST service with Spring RestTemplate.
RestTemplate restTemplate = new RestTemplate(); String fooResourceUrl = "https://openexchangerates.org/api/historical/"+line+".json?app_id=" +APIKEY; ClassRates forObject = restTemplate.getForObject(fooResourceUrl, ClassRates.class); |
Unmarshalling response and create Map, insert into db.
// Creating map with all required params Map<string, object=""> paramMap = new HashMap<string, object="">(); paramMap.put("id", i); paramMap.put("data_cur", line); nqu.update(INSERT_QUERY, paramMap); </string,></string,> |
We have a good table with 226 records for further analytics.
Create graph MS Excel.
Link to full project on GitHub:
Github USDHistoricalRateProject