- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Get the real time currency exchange rate?
Python is very good at handling API calls. In this article we will see how we can handle the API calls for currency exchange rates in real time as well as historical.
Using forex-python
This module provides the most direct way of getting the currency conversion rates. It has functions and parameters which can take inputs for the required currency codes and then give the result for the conversion. The below example gives the live conversion rate.
Example
from forex_python.converter import CurrencyRates c = CurrencyRates() print(c.get_rate('USD', 'GBP'))
Output
Running the above code gives us the following result −
0.7357387755
Historical currency rates
We add a datetime object form the datetime module to the above example and that gives us the currency exchange rate at specific time and date.
Example
from forex_python.converter import CurrencyRates import datetime c = CurrencyRates() dt = datetime.datetime(2020, 3, 27, 11, 21, 13, 114505) print(c.get_rate('USD', 'INR', dt))
Output
Running the above code gives us the following result −
75.4937596793
Using web API
There are many APIs available which provide us the currency rates by making calls using a API key and getting back the result as JSON. We can further extend the code to convert the JSON to a list and format the data if needed.
Example
import requests # Where USD is the base currency you want to use url = 'https://v6.exchangerate-api.com/v6/336ccxxxxxxxxx8e74eac/latest/USD' # Making our request response = requests.get(url) data = response.json() # Your JSON object print(data)
Output
Running the above code gives us the following result −
{'result': 'success', 'documentation': 'https://www.exchangerate-api.com/docs', 'terms_of_use': 'https://www.exchangerate-api.com/terms', 'time_last_update_unix': 1610323201, 'time_last_update_utc': 'Mon, 11 Jan 2021 00:00:01 +0000', 'time_next_update_unix': 1610409616, 'time_next_update_utc': 'Tue, 12 Jan 2021 00:00:16 +0000', 'base_code': 'USD', 'conversion_rates': {'USD': 1, 'AED': 3.6725, ………., 'XOF': 536.3826, 'XPF': 97.579, 'YER': 250.1264, 'ZAR': 15.2899, 'ZMW': 21.1561}}