Seamlessly Integrate a Currency Exchange API into Your Spring Boot Application

Step 1: Obtain a Rapid API Key

To begin, you’ll need to sign up for a Rapid API account and obtain an API key. Rapid API is a popular platform that provides access to a wide range of APIs, including currency exchange APIs. Once you have your API key, you’ll be able to securely access the currency exchange API and integrate it into your Spring Boot application.

Step 2: Set Up the Currency Exchange Service

Next, you’ll need to create a dedicated service class to handle the communication with the currency exchange API. This class will be responsible for fetching the latest exchange rates and providing them to your Spring Boot application.

Create the CurrencyExchangeService Class

Start by creating a new package called “currency” in your Spring Boot project. Within this package, create a class called “CurrencyExchangeService”. This class will contain the logic for interacting with the Rapid API currency exchange endpoint.

Implement the API Call

Inside the CurrencyExchangeService class, you’ll need to add a method that makes the API call to Rapid API and retrieves the latest exchange rates. You can use the provided code example from the Rapid API documentation as a starting point:


public List<String> getExchangeRates() {
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://currency-exchange.p.rapidapi.com/list"))
                .header("X-RapidAPI-Key", "YOUR_API_KEY_HERE")
                .header("X-RapidAPI-Host", "currency-exchange.p.rapidapi.com")
                .method("GET", HttpRequest.BodyPublishers.noBody())
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return Arrays.asList(response.body().split(","));
    } catch (IOException | InterruptedException e) {
        throw new RuntimeException("Error fetching exchange rates", e);
    }
}

Remember to replace “YOUR_API_KEY_HERE” with your actual Rapid API key.

Step 3: Create a Spring Boot Controller

Now that you have the CurrencyExchangeService set up, you can create a Spring Boot controller to handle the currency exchange functionality in your application. This controller will expose an endpoint that returns the list of available currencies.

Create the CurrencyController Class

In your Spring Boot project, create a new controller class called “CurrencyController”. This class will be responsible for handling the currency exchange-related requests and responses.

Implement the Currency Exchange Endpoint

Inside the CurrencyController class, add a method that returns the list of available currencies. This method will use the CurrencyExchangeService to fetch the exchange rates and pass them to the view:


@Controller
public class CurrencyController {
    private final CurrencyExchangeService currencyExchangeService;

    public CurrencyController(CurrencyExchangeService currencyExchangeService) {
        this.currencyExchangeService = currencyExchangeService;
    }

    @GetMapping("/")
    public String getCurrencyExchangePage(Model model) {
        List<String> exchangeRates = currencyExchangeService.getExchangeRates();
        model.addAttribute("exchangeRates", exchangeRates);
        return "index";
    }
}

Step 4: Create the View Template

The final step is to create a Thymeleaf template that will display the list of available currencies. In your Spring Boot project, create a new folder called “templates” in the “resources” directory. Inside the “templates” folder, create a new file called “index.html”.

Populate the Index Template

In the “index.html” file, you can use Thymeleaf syntax to display the list of exchange rates fetched from the CurrencyExchangeService:


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Currency Exchange</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1>Currency Exchange</h1>
        <table class="table">
            <thead>
                <tr>
                    <th>Currency</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="rate : ${exchangeRates}">
                    <td th:text="${rate}"></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

Step 5: Run the Application

With the CurrencyExchangeService, CurrencyController, and index.html template in place, you can now run your Spring Boot application. When you visit the root URL (e.g., http://localhost:8080/), you should see a table displaying the list of available currencies fetched from the Rapid API currency exchange endpoint.

Conclusion

In this blog post, you’ve learned how to seamlessly integrate a currency exchange API into your Spring Boot application. By following the steps outlined, you can now easily fetch the latest exchange rates and display them in a user-friendly interface. This is just the beginning – in the next tutorial, we’ll explore how to add a form to your application, allowing users to convert between different currencies using the API. Stay tuned and keep coding!

Check out the code at GitHub by clicking here!

If you’re interested in taking your development skills to the next level, be sure to check out The Nerdic Coder Academy. I’ll guide you every step of the way on how to build high-quality web applications.

And don’t forget to check out my Spring Boot development in VSCode Part 1 video on YouTube. It’s a great resource for getting started with modern Java Spring Boot development using VSCode.

One thought on “Seamlessly Integrate a Currency Exchange API into Your Spring Boot Application

Add yours

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑