Real time currency convertor in Python
For making a currency convertor in Python using fixer.io API the following are the pre-requisites you should have knowledge about.
- Basic knowledge of Python syntax.
- Have knowledge of the dictionary and its methods in Python.
- What is JSON?
- Sign up on fixer.io and get your API_KEY.
Python program: Currency conversion using fixer.io API
import requests import json api_url_end='http://data.fixer.io/api/latest?access_key=API_KEY' def currency_convertor(currency_from,currency_to,amount): rate=response.json()['rates'][currency_from] amount_in_EUR=amount/rate result=amount_in_EUR*(response.json()['rates'][currency_to]) print(result) response=requests.get(api_url_end) base_currency=input('Enter the base currency from '+str(response.json()['rates'].keys())) convert_to=input('Enter the result currency '+str(response.json()['rates'].keys())) amount_to_convert=int(input("Enter the amount to convert")) currency_convertor(base_currency,convert_to,amount_to_convert)
So let’s understand how the code works and our task of currency conversion is carried on. We will go line by line so don’t worry I will be explaining everything.
Lines 1 and 2 are simple to import statements for importing requests and JSON. If you don’t have requests library install you can get it done by writing the following code into command prompt or command line.
pip install requests
In line 3 we are declaring api_url_end as a global variable that holds the value for the URL end through which we receive data from the API. ( CAUTION: you have to replace API_KEY which you will get after signing up on fixer.io).
Line 12 (don’t worry will be explaining the function as well) we are using get method of the requests library to retrieve data from the API and storing this data in a variable named response.
In line 13-15 we take the user input for the base_currency, currenty_to, and amount_to_convert. Here, response.json() gives data in the form of a dictionary (you can see the format of data in the documentation of fixer.io).
We define a function currency_convertor which takes 3 input arguments i.e. currency_from, currency_to, amount. Defining rate as a variable which stores the rate of the base currency. We then calculate the amount_in_EUR as the base currency for the data received is EUR.
And finally, the result will be the amount_in_EUR multiplied by the rate of currency_to.