Currency conversion is a crucial aspect of international trade and foreign transactions. Thus, foreign investors and businesses frequently use currency converter apps to get accurate real-time exchange rates. Travellers also need currency conversion data to get the best exchange rate data. In this tutorial, we’ll show you how to create a Python currency converter app using a currency conversion API and Python Flask.
Table of Contents
Choosing a Currency Conversion API for Our Python Currency Converter
For this tutorial, we’ll use CurrencyLayer API, which provides highly accurate and reliable exchange rates and currency conversion data. CurrencyLayer’s data powers numerous currency converters, back-office systems, and mobile apps worldwide.
Here are the other prominent features of the API that make it the best choice for our Python currency converter:
- With CurrencyLayer exchange rate API, you can access up to 168 world currencies and precious metals.
- The Forex API Python updates data frequently to provide accurate and real-time rates. Data updates range from every 60 minutes down to stunning 60 seconds, depending on your subscription plan.
- CurrencyLayer is super easy to integrate into any web app. It also comes with detailed documentation containing sample code, further easing the integration process.
- The API delivers JSON data for maximum usability, ease of integration, and compatibility with any of your applications.
- With CurrenclyLayer API, you gain access to historical rates, have the API convert single amounts for you, get a currency’s change parameters, switch Source Currency, and more.
- The best part about CurrencyLayer is that it comes with a free plan offering 100 monthly API calls, daily updates, and historical rates.
How can I Empower Apps With Exchange Rate Data Using CurrencyLayer?
You can easily integrate CurrencyLayer into any application you have. For instance, we’ll use the CurrecyLayer Python currency converter API in our Flask Python web app.
You just have to make an API request using a simple URL structure, and the API will do the rest.
Here are examples of how you can get the data:
Live Data
Example API request:
1 |
https://api.currencylayer.com/live? access_key = YOUR_ACCESS_KEY & currencies = AUD,EUR,GBP,PLN |
Example API response:
Historical Data
The CurrencyLayer API delivers highly accurate historical exchange rate data for every past day all the way back to 1999. You can access historical rates by simply attaching the date parameter with a valid date (Format: YYYY-MM-DD) to the historical endpoint.
Example API request:
1 |
https://api.currencylayer.com/historical? access_key = YOUR_ACCESS_KEY& date = 2005-02-01 |
Example API response:
Convert One Currency to Another
With CurrencyLayer’s ‘convert’ endpoint, you can perform a Single currency conversion.
To use this endpoint, you simply need to specify the currency that you want to convert, the currency to which you want to convert, and the amount you would like to convert.
Example API request:
1 |
https://api.currencylayer.com/convert ? access_key = YOUR_ACCESS_KEY & from = USD & to = GBP & amount = 10 |
Example API response:
Do You Need More On API Endpoints?
The CurrencyLayer API also offers additional customizable endpoints. Below, you will find a summary of all available endpoints.
Moreover, you can specify
For both live and historical rates, you may limit your API request to a set of specific currencies by attaching the currencies parameter followed by any available 3-letter currency codes of your choice.
How To Create A Python Currency Converter App?
In this section, we’ll build a Python Flask web app that utilizes the CurrencyLayer API for currency conversion. You can follow this tutorial to learn how to integrate and interact with the API endpoints. To use the CurrencyLayer API, you first need to sign up and create a free account.
Start your PowerShell or Bash and type these commands to create a new folder and initialize a new Python Flask application.
1 2 3 4 5 6 7 8 |
0. mkdir PythonFlaskDemo 1. cd PythonFlaskDemo 2. touch app.py 3. py -m venv env 4. env\Scripts\activate 5. pip install flask 6. pip install requests 7. set FLASK_APP=app.py |
Here, we’re using VS Code, and we have already opened it with the “code ” command. Now copy this source code to your app.py and use HTML web pages for data representation (you can find the complete code from this GitHub repository)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
from flask import Flask, request, redirect, url_for import requests app = Flask(__name__) @app.route('/') def hello_world(): # put application's code here return 'Hello World!' @app.route('/result/<string:usd_aud>/<string:usd_eur>/<string:usd_gbp>') def result_realtime(usd_aud, usd_eur, usd_gbp): return "<h3>USDAUD: {}; <br>USDEUR: {}; <br>USDGBP: {}</h3>".format(usd_aud, usd_eur, usd_gbp) @app.route('/rtrates', methods=['GET', 'POST']) def rtrates(): if request.method == 'GET': return '''<h1>Please fill out the parameters</h1> <form method="POST" action="/rtrates"> <input type="text" name="acc_key" value="c92b0e664f8dd7743333fed2f42fd6c9"> <input type="text" name="currencies" value="AUD,EUR,GBP"> <input type="submit" value="Request"> </form>''' else: acc_key = request.form['acc_key'] currencies = request.form['currencies'] req = requests.get('https://api.currencylayer.com/live?access_key=' + acc_key + '¤cies=' + currencies) response = req.json() usd_aud = response['quotes']['USDAUD'] usd_eur = response['quotes']['USDEUR'] usd_gbp = response['quotes']['USDGBP'] return redirect(url_for('result_realtime', usd_aud=usd_aud, usd_eur=usd_eur, usd_gbp=usd_gbp)) @app.route('/result/<string:from_c>/<string:to_c>/<string:amount>/<string:quote>/<string:result>') def result_conversion(from_c, to_c, amount, quote, result): return "<h3>From: {}; <br>To: {}; <br>Amount: {}; <br> Result: {}; <br> Quote: {};</h3>" \ .format(from_c, to_c, amount, result, quote) @app.route('/conversion', methods=['GET', 'POST']) def conversion(): if request.method == 'GET': return '''<h1>Please fill out the parameters</h1> <form method="POST" action="/conversion"> <input type="text" name="acc_key" value="c92b0e664f8dd7743333fed2f42fd6c9"> <input type="text" name="from" value="from"> <input type="text" name="to" value="to"> <input type="text" name="amount" value="amount"> <input type="submit" value="Request"> </form>''' else: acc_key = request.form['acc_key'] from_c = request.form['from'] to_c = request.form['to'] amount = request.form['amount'] req = requests.get( 'https://api.currencylayer.com/convert?access_key=' + acc_key + '&from=' + from_c + "&to=" + to_c + "&amount=" + amount) response = req.json() quote = response['info']['quote'] result = response['result'] return redirect( url_for('result_conversion', from_c=from_c, to_c=to_c, amount=amount, quote=quote, result=result)) if __name__ == '__main__': app.run() |
Explanation
As you can see, we have two simple endpoint calling functions and two functions to represent the received data to the user. It is straightforward. It gets the submitted data, builds up a URL string, and sends it as a request.
- @app.route(‘/result/<string:usd_aud>/<string:usd_eur>/<string:usd_gbp>’): This route expects three string parameters representing the currencies conversion from USD to AUD, EUR, and GBP. It returns HTML displaying these rates.
- @app.route(‘/rtrates’): This route handles both GET and POST requests. It displays a form for users to input their account key and desired currencies. On submission, it makes a request to the CurrencyLayer API to get real-time exchange rates and redirects to the result_realtime route.
- @app.route(‘/result/<string:from_c>/<string:to_c>/<string:amount>/<string:quote>/<string:result>’): This route expects five string parameters representing the conversion details. It returns HTML displaying these details.
- @app.route(‘/conversion’): Similar to /rtrates, this route handles both GET and POST requests. It displays a form for users to input their account key, source currency, target currency, and amount. On submission, it makes a request to the CurrencyLayerl API to perform currency conversion and redirects to the result_conversion route.
Note: Remember to add your unique API key to the above code.
How To Run Our CurrencyLayer API-based Python Currency Converter Web Application?
Depending on the configuration of your system, you can run your Flask web application with these commands.
Demo in Action!
Fill out the form by using your desired currencies; source currency or base currency, target currency, and amount.
Conversion Result
Conclusion
Currency conversion means the rate or value for which one currency, such as the Australian dollar, is exchanged for another currency, such as the Canadian dollar. Businesses and investors often need to convert currencies for international trade, foreign transactions, financial analysis, and mitigating financial risks. Travellers also need currency conversion to get accurate exchange rates when travelling to another country. Thus, currency converter apps are in demand.
In this tutorial, we’ve created a simple Python currency converter app using an exchange rate Python API and Flask Python. We’ve used the CurrencyLayer API for our tutorial as it’s a reliable currency converter API Python that provides highly accurate exchange rate data. The API supports real-time and historical exchange rate data. It also offers a separate currency conversion endpoint that you can use to convert any amount from one currency to the target currency.
Frequently Asked Questions (FAQs)
How to convert currency in Python?
You can create a Python currency converter app using a currency converter API like the one we created in this tutorial.
How do you get live currency rates in Python?
You can use a currency conversion API like CurrencyLayer to integrate real-time/live currency exchange rates in your Python currency converter app.
How to easily convert currency?
You can use CurrencyLayer API to convert one currency to another easily. The API supports 168 world currencies, such as British Pound, Japanese Yen, Indian rupee, Kuwaiti dinar, US dollar, Hong Kong dollar, and more.