How to Get Exchange Rates in Python
How to Get Exchange Rates in Python
Fetching exchange rates programmatically is a crucial capability for developers working in finance, trading applications, or even for personal projects. In this guide, we’ll walk you through the process of using the CurrencyRest API to get real-time and historical exchange rates in Python, showcasing error handling and caching mechanisms along the way.
Step 1: Setting Up Your Environment
Before getting started, ensure you have Python installed on your machine. You will need the requests library to make API calls:
pip install requests
Step 2: Understanding the CurrencyRest API
CurrencyRest provides a straightforward REST API that can be accessed to get the latest and historical exchange rates. With support for 108 fiat currencies and 94 cryptocurrencies, it allows you to convert currencies and get detailed information about them.
Step 3: Making Your First API Call
To get started, you need to make a GET request to the CurrencyRest API. Here’s how you can convert 100 USD to XOF (West African CFA Franc):
import requests
def get_exchange_rate(from_currency, to_currency, amount):
url = f'https://api.currencyrest.com/api/v1/convert?from={from_currency}&to={to_currency}&amount={amount}'
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for bad responses
data = response.json() # Convert response to JSON
return data
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
# Example usage
result = get_exchange_rate('USD', 'XOF', 100)
print(result)
Step 4: Implementing Error Handling
In the code provided, we use try/except blocks to capture possible errors such as network issues or unexpected responses. This is crucial for building robust applications.
Step 5: Caching Results for Efficiency
To reduce the number of API requests (and enhance performance), implement a caching mechanism. Here’s a basic example using a dictionary to store previously fetched rates:
cache = {}
def get_cached_exchange_rate(from_currency, to_currency, amount):
cache_key = f'{from_currency}_{to_currency}'
if cache_key in cache:
return cache[cache_key] * amount # Return cached value if exists
else:
rate = get_exchange_rate(from_currency, to_currency, 1)['result']['rate']
cache[cache_key] = rate # Store in cache
return rate * amount
# Example usage
cached_result = get_cached_exchange_rate('USD', 'XOF', 100)
print(cached_result)
Step 6: Exploring Further Capabilities
The CurrencyRest API supports a variety of features including historical rates and more detailed currency information which you can explore in the CurrencyRest API documentation.
Conclusion
With CurrencyRest, fetching exchange rates in Python is quick and easy. Start building your applications today and take advantage of our Free Tier: 300 requests per month with full access to every currency pair! Sign up now to get started!
CurrencyRest
Author