Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC - Getting Cryptocurrency Details using REST API

Fetching cryptocurrency details using a REST API in a Spring MVC application involves calling an external service, parsing the returned data, and presenting it to the user. There are many cryptocurrency APIs out there, like CoinGecko, CoinMarketCap, and more.

For this guide, let's use the CoinGecko API as an example, which offers a free tier and is easy to integrate with.

1. Set up Spring Boot with Spring MVC:

Add the necessary dependencies to your pom.xml:

<dependencies>
    <!-- Spring Boot Web Starter for Spring MVC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- For calling REST APIs -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
</dependencies>

2. Create a Service to Fetch Cryptocurrency Details:

@Service
public class CryptoService {

    @Autowired
    private WebClient.Builder webClientBuilder;

    public Map<String, Object> getCryptoDetails(String cryptoId) {
        String apiUrl = "https://api.coingecko.com/api/v3/coins/" + cryptoId;

        // Fetch crypto details
        Map<String, Object> response = webClientBuilder.build()
            .get()
            .uri(apiUrl)
            .retrieve()
            .bodyToMono(Map.class)
            .block();

        return response;
    }
}

Here, WebClient from the spring-boot-starter-webflux module is used to fetch data from CoinGecko's REST API.

3. Create a Controller:

@Controller
@RequestMapping("/crypto-details")
public class CryptoController {

    @Autowired
    private CryptoService cryptoService;

    @GetMapping
    public String getCryptoForm() {
        return "cryptoForm";  // Return your form view
    }

    @PostMapping
    public String fetchCryptoDetails(@RequestParam String cryptoId, Model model) {
        Map<String, Object> details = cryptoService.getCryptoDetails(cryptoId);
        model.addAttribute("details", details);
        return "cryptoResult";  // Return your result view
    }
}

4. Create Views (e.g., with Thymeleaf):

cryptoForm.html:

<form action="/crypto-details" method="post">
    Cryptocurrency ID (e.g. bitcoin, ethereum): <input type="text" name="cryptoId">
    <input type="submit" value="Get Details">
</form>

cryptoResult.html:

<h2>Cryptocurrency Details:</h2>
<p>Name: <span th:text="${details['name']}"></span></p>
<p>Current Price: <span th:text="${details['market_data']['current_price']['usd']}"></span> USD</p>
<!-- Add more details as needed -->

5. Run & Test:

Now, run your Spring Boot application and navigate to /crypto-details. Enter the ID of a cryptocurrency (like bitcoin or ethereum) to see its details.

Note: Always check the documentation of the API you're using. Some APIs might require you to sign up and get an API key, while others might have request rate limits or other constraints. Ensure your application respects these limits and terms of use. Also, remember to handle errors gracefully, like when the API is down or the provided cryptocurrency ID doesn't exist.

  1. Spring MVC Cryptocurrency Details REST API Example:

    • Description: This is a basic example illustrating how to use a REST API to fetch cryptocurrency details in a Spring MVC application. It typically involves making a request to an external cryptocurrency API.

    • Code Snippet: (Controller Method with RestTemplate)

      @Controller
      public class CryptoDetailsController {
          @GetMapping("/getCryptoDetails")
          @ResponseBody
          public String getCryptoDetails(@RequestParam("symbol") String symbol) {
              // Use RestTemplate to make a request to the cryptocurrency API
              // Parse the response and return cryptocurrency details
              return "Details for " + symbol + ": Price $50, Market Cap $1B";
          }
      }
      
  2. Using REST API to Get Cryptocurrency Information in Spring MVC:

    • Description: This example extends the basic cryptocurrency details example by using a specific REST API to get live cryptocurrency information.

    • Code Snippet: (Controller Method with Cryptocurrency API)

      @Controller
      public class CryptoDetailsController {
          @GetMapping("/getCryptoDetails")
          @ResponseBody
          public String getCryptoDetails(@RequestParam("symbol") String symbol) {
              // Use RestTemplate to make a request to a cryptocurrency API
              // Parse the response and return cryptocurrency details
              return "Details for " + symbol + ": Price $60, Market Cap $1.5B";
          }
      }
      
  3. Consuming Cryptocurrency API in Spring MVC:

    • Description: This example focuses on the client-side of consuming an external cryptocurrency API using Spring's RestTemplate.

    • Code Snippet: (RestTemplate Usage)

      RestTemplate restTemplate = new RestTemplate();
      ResponseEntity<String> response = restTemplate.getForEntity("https://api.cryptocurrencyapi.com/details/BTC", String.class);
      String cryptoDetails = response.getBody();
      
  4. RESTful Cryptocurrency Details Endpoint in Spring MVC:

    • Description: This example demonstrates creating a RESTful endpoint in Spring MVC that provides cryptocurrency details based on a given symbol.

    • Code Snippet: (RestController)

      @RestController
      public class CryptoDetailsRestController {
          @GetMapping("/api/cryptoDetails")
          public ResponseEntity<String> getCryptoDetails(@RequestParam("symbol") String symbol) {
              // Logic to fetch and return cryptocurrency details
              return ResponseEntity.ok("Details for " + symbol + ": Price $70, Market Cap $2B");
          }
      }
      
  5. Retrieving Cryptocurrency Details with Spring RestTemplate:

    • Description: This example showcases the usage of RestTemplate to retrieve cryptocurrency details from an external API in a Spring MVC application.

    • Code Snippet: (Service Class)

      public class CryptoDetailsService {
          private final String cryptoApiUrl = "https://api.cryptocurrencyapi.com/details/BTC";
      
          public String getCryptoDetails() {
              RestTemplate restTemplate = new RestTemplate();
              ResponseEntity<String> response = restTemplate.getForEntity(cryptoApiUrl, String.class);
              return response.getBody();
          }
      }
      
  6. Spring MVC Cryptocurrency Information Display:

    • Description: This example involves displaying cryptocurrency information retrieved from an external API in a Spring MVC application.

    • Code Snippet: (Controller Method)

      @Controller
      public class CryptoDisplayController {
          @Autowired
          private CryptoDetailsService cryptoDetailsService;
      
          @GetMapping("/displayCryptoInfo")
          public String displayCryptoInfo(Model model) {
              String cryptoDetails = cryptoDetailsService.getCryptoDetails();
              // Process cryptocurrency details and return result
              model.addAttribute("result", cryptoDetails);
              return "cryptoInfoDisplay";
          }
      }
      
  7. External API Integration for Cryptocurrency Details in Spring MVC:

    • Description: This example illustrates the integration of an external cryptocurrency API into a Spring MVC application.

    • Code Snippet: (Service Integration)

      public class CryptoDetailsService {
          private final String cryptoApiUrl = "https://api.cryptocurrencyapi.com/details/BTC";
      
          public String getCryptoDetails() {
              RestTemplate restTemplate = new RestTemplate();
              ResponseEntity<String> response = restTemplate.getForEntity(cryptoApiUrl, String.class);
              return response.getBody();
          }
      }
      
  8. Fetching Real-Time Cryptocurrency Data in Spring MVC:

    • Description: This example focuses on fetching real-time cryptocurrency data from an external API and displaying it in a Spring MVC application.

    • Code Snippet: (Controller Method)

      @Controller
      public class CryptoDisplayController {
          @Autowired
          private CryptoDetailsService cryptoDetailsService;
      
          @GetMapping("/realTimeCryptoData")
          public String showRealTimeCryptoData(Model model) {
              String cryptoDetails = cryptoDetailsService.getCryptoDetails();
              // Process cryptocurrency details and return result
              model.addAttribute("result", cryptoDetails);
              return "cryptoDetails";
          }
      }
      
  9. Building a Cryptocurrency Information Service with Spring MVC and REST:

    • Description: This example combines the features of a cryptocurrency information service with real-time cryptocurrency details obtained from an external REST API.

    • Code Snippet: (Crypto Details Controller)

      @Controller
      public class CryptoDetailsController {
          @Autowired
          private CryptoDetailsService cryptoDetailsService;
      
          @GetMapping("/cryptoInfoService")
          public String showCryptoInfoService(Model model) {
              String cryptoDetails = cryptoDetailsService.getCryptoDetails();
              // Process cryptocurrency details and return result
              model.addAttribute("result", cryptoDetails);
              return "cryptoInfoServiceResult";
          }
      }