In today’s globalized world, currency conversion is a common task that many individuals and businesses encounter. Whether you’re a traveler planning your expenses or a business owner dealing with international transactions, having a reliable currency converter can be invaluable. In this blog post, we will explore how to build a real-time currency converter using Python, leveraging the Exchange Rates API to retrieve up-to-date exchange rates.
Python is a powerful programming language with a vast ecosystem of libraries that make it an ideal choice for web scraping, data manipulation, and API integration. To retrieve exchange rates from Exchange Rates API, we will utilize the popular requests module. This module allows us to make HTTP requests and interact with web APIs effortlessly. If you haven’t already installed the requests module, let’s go through the installation process before diving into the currency converter implementation.
Installing the Requests Module:
The requests module can be easily installed using pip, the package installer for Python. Open your command-line interface and execute the following command:
python -m pip install requests
This will download and install the requests module along with its dependencies. Once the installation is complete, we can proceed with building our real-time currency converter.
Implementing the Currency Converter Class
To interact with the Exchange Rates API and perform currency-related operations, we’ll start by implementing the CurrencyConverter class. This class encapsulates the functionality to fetch the latest exchange rates, perform currency conversion, retrieve historical rates, and more.
import requests
class RequestError(Exception):
"""Exception raised for errors in the API request."""
pass
class CurrencyConverter:
"""
A simple class for interacting with a currency conversion API.
Attributes:
__base_uri (str): The base URI of the currency conversion API.
__access_key (str): The access key required for API authentication.
"""
def __init__(self, access_key):
"""
Initialize the CurrencyConverter object.
Args:
access_key (str): The access key required for API authentication.
"""
self.__base_uri = 'http://api.exchangerate.host'
self.__access_key = access_key
def live(self, **params):
"""
Get the most recent exchange rate data.
Args:
**params: Additional query parameters for the API request.
Returns:
dict: JSON response containing the latest exchange rates.
Raises:
RequestError: If the API request fails.
"""
return self.__api_request('/live', params)
def convert(self, cfrom: str, cto: str, amount: float, **params):
"""
Convert an amount from one currency to another.
Args:
cfrom (str): Source currency code.
cto (str): Target currency code.
amount (float): Amount to be converted.
**params: Additional query parameters for the API request.
Returns:
dict: JSON response containing the converted amount.
Raises:
RequestError: If the API request fails.
"""
params = {**params, 'from': cfrom, 'to': cto, 'amount': amount}
return self.__api_request('/convert', params)
def historical(self, date: str, **params):
"""
Get historical rates for a specific day.
Args:
date (str): Date for which to retrieve historical rates in the format 'YYYY-MM-DD'.
**params: Additional query parameters for the API request.
Returns:
dict: JSON response containing the historical exchange rates.
Raises:
RequestError: If the API request fails.
"""
params = {**params, 'date': date}
return self.__api_request(f'/historical', params)
def timeframe(self, start_date: str, end_date: str, **params):
"""
Request exchange rates for a specific period of time.
Args:
start_date (str): Start date of the time range in the format 'YYYY-MM-DD'.
end_date (str): End date of the time range in the format 'YYYY-MM-DD'.
**params: Additional query parameters for the API request.
Returns:
dict: JSON response containing the exchange rates for the specified time range.
Raises:
RequestError: If the API request fails.
"""
params = {**params, 'start_date': start_date, 'end_date': end_date}
return self.__api_request('/timeframe', params)
def change(self, currencies: str, **params):
"""
Request any currency's change parameters (margin, percentage).
Args:
currencies (str): The currency code for which to retrieve change parameters.
**params: Additional query parameters for the API request.
Returns:
dict: JSON response containing the exchange rate fluctuations for the specified time range.
Raises:
RequestError: If the API request fails.
"""
params = {**params, 'currencies': currencies}
return self.__api_request('/change', params)
def list(self, **params):
"""
Retrieve a full list of supported currencies.
Args:
**params: Additional query parameters for the API request.
Returns:
dict: JSON response containing the supported currencies.
Raises:
RequestError: If the API request fails.
"""
return self.__api_request('/list', params)
@property
def base_uri(self):
"""
Get the base URI of the API.
Returns:
str: Base URI as a string.
"""
return self.__base_uri
def __api_request(self, path, params):
"""
Make an API request to the specified path with the given parameters.
Args:
path (str): API path.
params (dict): Query parameters for the API request.
Returns:
dict: JSON response from the API.
Raises:
RequestError: If the API request fails.
"""
try:
params = {**params, "access_key": self.__access_key}
response = requests.get(f'{self.__base_uri}{path}', params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.ConnectionError as error:
raise RequestError("Failed to make API request") from error
After implementing the CurrencyConverter class, we can now utilize its functionalities to interact with the Exchange Rates API and perform various currency-related operations. In the code snippet below, we demonstrate how to use the CurrencyConverter class:
from converter import CurrencyConverter, RequestError
if __name__ == '__main__':
try:
# Initialize the CurrencyConverter with an access key
converter = CurrencyConverter("5edf6c440cdaa42336d949XXXXXXXXXX")
# Fetch the latest exchange rates
latest_rates = converter.live()
print("Latest Exchange Rates:")
print(latest_rates)
# Convert currency from USD to ZMW
conversion = converter.convert('USD', 'ZMW', 100)
print("Conversion Result:")
print(conversion)
# Fetch historical exchange rates for a specified date
historical = converter.historical('2022-01-01')
print("Historical Exchange Rates:")
print(historical)
# Fetch exchange rates for specified dates
timeseries = converter.timeframe('2022-01-01', '2022-12-31')
print("Exchange Rate Timeframe:")
print(timeseries)
# Fetch change parameters for currencies
change = converter.change("USD,EUR")
print("Change Parameters:")
print(change)
# Fetch supported currencies
currencies = converter.list()
print("Supported Currencies:")
print(currencies)
except RequestError:
# Handle the case where the API request fails
print('Failed to retrieve exchange rates.')
That was all I had to share with you guys. If you found this code informative and would love to see more, don’t forget to subscribe to our newsletter! 😊