Problem : Fetch the open exchange for an input date, base currency and exchange currency.
The below python script leverages open exchange rates API . Reference to GIST with self explanatory comments in the code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import os | |
def fetchExchangeRate(currencyDate, baseCurrency, currencySymbol): | |
""" | |
Method to fetch open Currency exchange rate of base currency (1 Unit) to a currencySymbol | |
Reference : https://docs.openexchangerates.org/reference/api-introduction | |
Args: | |
currencyDate: Date for which you need open exchange rate. | |
baseCurrency: ISO currency code | |
currencySymbol: ISO currency codes | |
Returns: | |
JSON response of Open Exchange Rate | |
""" | |
url = "https://openexchangerates.org/api/historical/{currencyDate}.json?base={base}&symbols={symbol}".format(currencyDate=currencyDate, base=baseCurrency, symbol=currencySymbol) | |
open_exchange_token = os.environ.get("OPEN_EXCHANGE_TOKEN") | |
headers = { | |
"Authorization": f"Token {open_exchange_token}", # Replace with your API token or other headers | |
"Content-Type": "application/json", # Adjust as needed | |
} | |
print(url) | |
response = requests.get(url, headers=headers) | |
if response.status_code == 200: | |
# Process successful response | |
data = response.json() # If the response is JSON | |
print(data) | |
else: | |
# Handle error | |
print("Request failed with status code:", response.status_code) | |
print("Response text:", response.text) |
Sample Response for the below invocation
openExchange.fetchExchangeRate("2023-01-25","INR", "GBP")
{
'disclaimer': 'Usage subject to terms: https://openexchangerates.org/terms',
'license': 'https://openexchangerates.org/license',
'timestamp': 1674691198,
'base': 'INR',
'rates': {
'GBP': 0.009886
}
}