Spring MVC - Getting Cryptocurrency Details using REST API
Last Updated :
29 Jul, 2022
Cryptocurrencies are a hot topic throughout the world. Trading with cryptocurrency got both pros and cons. Nowadays REST APIs are very useful to get much information including cryptocurrencies. In this article, we are going to see about one such REST API call to get cryptocurrency detail. We are going to retrieve the information by using Spring MVC. Examples of cryptocurrency:
- Bitcoin (BTC)
- Litecoin (LTC)
- Ethereum (ETH)
- Zcash (ZEC)
- and many more
By using the above URL, let us try to give the cryptocurrency name and check the output
https://api.coincap.io/v2/assets/bitcoin
It produces the JSON output and it is given below
Now for our Spring MVC implementation of retrieving REST API calls, let's show the below details like
Rank : 1
Symbol : BTC
Price(USD): 23016.1293786598184909
Step by Step Implementation
Via a Maven-driven project, implementation is getting done. Let's start with the project structure
Project Structure:
As it is a maven-driven project, let us go with pom.xml
pom.xml
XML
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cryptocurrency.cryptocurrency_Rest_API</groupId>
<artifactId>cryptocurrency_Rest_API</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>profileGenerator</name>
<url>http://maven.apache.org</url>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<spring-version>5.1.0.RELEASE</spring-version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- JSTL Dependency -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Servlet Dependency -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP Dependency -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>CryptoDetails</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- This should be added to overcome Could not initialize class
org.apache.maven.plugin.war.util.WebappStructureSerializer -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
</plugins>
</build>
</project>
Invocation file: findCryptoDetails.jsp
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cryptocurrency</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<style type="text/css">
.main-form, .profile-area {
width: 500px;
}
.main-form {
margin: 50px auto 0px;
}
.profile-area {
margin: 10px auto;
}
.main-form section, .profile-area section {
margin-bottom: 15px;
background: #1BA330;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
}
.main-form section {
padding: 30px;
}
.profile-area section {
padding: 30px 30px 30px;
}
.profile-area section > div {
text-align: center;
}
.main-form h3 {
margin: 0 0 15px;
}
.form-control, .btn {
min-height: 38px;
border-radius: 2px;
}
.btn {
font-size: 15px;
font-weight: bold;
font-family: verdana;
}
.hideElement {
display: none;
}
</style>
</head>
<body>
<div class="main-form" id="main-form">
<section>
<h5 class="text-center">Enter Cryptocurrency</h5>
<div class="form-group">
<input id="cryptocurrency" type="text" class="form-control" placeholder="Enter cryptocurrency here..." required="required">
</div>
<div class="form-group">
<button onclick="loadData()" class="btn btn-primary btn-block">Find Cryptocurrency Details</button>
</div>
</section>
</div>
<div class="profile-area hideElement" id="profile-area">
<section>
<div id="loader" class="hideElement">
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
<div id="profile" class="hideElement">
<br><br>
<p><strong>Rank : </strong><span id="rank"></span></p>
<p><strong>Symbol : </strong><span id="symbol"></span></p>
<p><strong>Price(USD): </strong><span id="priceUsd"></span></p>
</div>
</section>
</div>
</body>
<script>
function loadData() {
document.getElementById("profile-area").classList.remove("hideElement");
document.getElementById("loader").classList.remove("hideElement");
document.getElementById("profile").classList.add("hideElement");
var cryptocurrency = document.getElementById("cryptocurrency").value;
if(cryptocurrency != "" && cryptocurrency != null) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("rank").innerHTML = jsonResponse.rank;
document.getElementById("symbol").innerHTML = jsonResponse.symbol;
document.getElementById("priceUsd").innerHTML = jsonResponse.priceUsd;
document.getElementById("loader").classList.add("hideElement");
document.getElementById("profile").classList.remove("hideElement");
}
};
xhttp.open("GET", "getCryptocurrencyDetailsByName?cryptocurrency=" + cryptocurrency, true);
xhttp.send();
console.log("done");
} else {
console.log("Enter cryptocurrency...")
}
}
</script>
</html>
This JSP file has to be run on any web server like Tomcat. On execution of the file, we can see the below output.
Output:
We need to give cryptocurrency value here. It can be bitcoin or ethereum etc.,
Let us check for bitcoin
Let us see the important java files that got used for the project
AppConfig.java
Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.cryptocurrency.cryptocurrency_Rest_API" })
public class AppConfig {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
return resolver;
}
}
SpringMvcDispatcherServletInitializer.java
Java
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcDispatcherServletInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
CryptocurrencyController.java
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.StringTokenizer;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
@Controller
public class CryptocurrencyController {
@RequestMapping("/getCryptocurrencyDetailsByName")
public @ResponseBody
JsonObject getCryptocurrencyDetails(String cryptocurrency) throws IOException {
JsonObject jsonObject = new JsonObject();
String data = getCryptocurrencyData(cryptocurrency);
// Once we receive the data we need to parse that
// and hence these special characters has to be removed
data = data.replaceAll("^\"|\"$", "");
StringTokenizer jsonTokenizer = new StringTokenizer(data,",");
String internalData[];
String expectedCryptocurrencyOutput = null;
// After parsing, retrieving Rank, Symbol and priceUsd from it
while (jsonTokenizer.hasMoreTokens()) {
expectedCryptocurrencyOutput = jsonTokenizer.nextToken();
internalData = StringUtils.split(expectedCryptocurrencyOutput,":");
System.out.println(internalData[0]+internalData[1]);
if (internalData[0].substring(1,internalData[0].length()-1).equalsIgnoreCase("rank")) {
jsonObject.addProperty("rank", internalData[1].substring(1,internalData[1].length()-1));
}
if (internalData[0].substring(1,internalData[0].length()-1).equalsIgnoreCase("symbol")) {
jsonObject.addProperty("symbol", internalData[1].substring(1,internalData[1].length()-1));
}
if (internalData[0].substring(1,internalData[0].length()-1).equalsIgnoreCase("priceUsd")) {
jsonObject.addProperty("priceUsd", internalData[1].substring(1,internalData[1].length()-1));
}
}
jsonObject.addProperty("data", data);
return jsonObject;
}
private String getCryptocurrencyData(String cryptocurrency) throws IOException {
String data = null;
StringBuilder responseData = new StringBuilder();
JsonObject jsonObject = null;
URL url = null;
// REST API call that got used along with the search string
url = new URL("https://api.coincap.io/v2/assets/"+cryptocurrency);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
responseData.append(line);
}
jsonObject = new Gson().fromJson(responseData.toString(), JsonObject.class);
data = jsonObject.get("data").toString();
}
System.out.println(data);
return data;
}
}
Conclusion
REST APIs are lightweight, independent, highly scalable, and flexible. Because of these reasons, quite often required data are obtained via REST API. Many are available as open source calls. For a few, we need to get a proper API key (for security reasons) and also there are limitations in using that calls. The one which we covered is totally open-source and hence Spring Framework can easily retrieve the data using a parsing mechanism, the required data is getting displayed on the screen.
Similar Reads
Spring MVC - Number Validation
The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
9 min read
Spring - MVC Form Checkbox
In this article, we will learn about the Spring MVC Checkbox and Checkboxes tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create checkboxes using form:checkbox and form:checkboxes tags. 'spring-form.tld' tag library In Spring Framework, we can use Java Server Pages
6 min read
Spring - MVC Form Radio Button
Here, we will learn about the Spring MVC radiobutton and radiobuttons tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create radiobuttons using form:radiobutton and form:radiobuttons tags. 'spring-form.tld' tag libraryIn Spring Framework, we can use Java Server Pages
8 min read
Spring - MVC Form Drop-Down List
In this article, we will learn about the Spring MVC Dropdown list. We will create a basic Spring MVC project in Spring tool suite(STS) to make a dropdown list using form:select tag. spring-form.tld We can use Java Server Pages (JSPs) as a view component in Spring Framework. To help you implement vie
7 min read
Spring - MVC TextArea
Here we will be learning about the Spring MVC TextArea form tag. We will create a basic Spring MVC project in the Spring tool suite(STS) to get some data from the user using the TextArea form tag. spring-form.tld We can use Java Server Pages (JSPs) as a view component in Spring Framework. To help y
7 min read
Spring - MVC Hidden Field
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this
6 min read
Spring - MVC Regular Expression Validation
Regular Expression Validation in Spring MVC can be achieved by using Hibernate Validator which is the implementation of Bean Validation API. Hibernate Validator provides @Pattern annotation which is used for regular expression validation. Syntax: @Pattern(regex="", flag="", message="") private Strin
4 min read
Spring - MVC Password
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this
8 min read
Spring - MVC Form Tag Library
Spring Framework provides spring's form tag library for JSP views in Spring's Web MVC framework. In Spring Framework, we use Java Server Pages(JSP) as a view component to interact with the user. From version 2.0, Spring Framework provides a comprehensive set of data binding-aware tags. These tags ar
14 min read
Spring - MVC Form Text Field
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this
8 min read