{"id":31782,"date":"2022-06-29T01:29:25","date_gmt":"2022-06-29T01:29:25","guid":{"rendered":"https:\/\/www.askpython.com\/?p=31782"},"modified":"2022-06-29T01:29:27","modified_gmt":"2022-06-29T01:29:27","slug":"build-currency-converter-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/build-currency-converter-python","title":{"rendered":"How to Build a Currency Converter in Python"},"content":{"rendered":"\n<p>Have you ever tried to offer a product, a service, or simply wanted to display prices in different currencies? Then you know how hard it can be to provide up-to-date and accurate exchange rates.<\/p>\n\n\n\n<p>This is where currency exchange APIs come in. An exchange API helps you handle your forex rate conversions. In this example, we will look at how to integrate a currency API into a simple Python application using the Flask web framework and a bit of Javascript for the front-end styling so you can build your own currency converter.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step-by-step guide on how to create a currency converter in Python<\/h2>\n\n\n\n<p>First, we will set up our development stack:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/www.python.org\/downloads\/\" target=\"_blank\" rel=\"noopener\">Python 3<\/a> (> 3.7)<\/li><li><a href=\"https:\/\/flask.palletsprojects.com\/en\/2.1.x\/installation\/\" target=\"_blank\" rel=\"noopener\">Flask<\/a><\/li><li><a href=\"https:\/\/nodejs.org\/en\/\" target=\"_blank\" rel=\"noopener\">Javascript<\/a> (Node)<\/li><li>Yarn (npm install &#8211;global yarn)<\/li><li>Vite\u00a0<\/li><li>Tailwind CSS\u00a0<\/li><li>postcss<\/li><li>autoprefixer<\/li><li>free <a href=\"https:\/\/currencyapi.com\/\" target=\"_blank\" rel=\"noopener\">currencyapi.com<\/a> API key<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Initializing our front-end project<\/h3>\n\n\n\n<p>To get started, we need to initialize a Vite project in our development workspace:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nyarn create vite currency-converter --template vanilla\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Step 2: Styling setup (optional)<\/h3>\n\n\n\n<p>Styling is optional, but if you choose to follow this step, we recommend using Tailwind CSS. Autoprefixer &#038; postcss further enable a smooth development experience. Therefore, we need to install these packages:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nyarn add -D tailwindcss postcss autoprefixer\n<\/pre><\/div>\n\n\n<p>Now we can initialize tailwind. This creates a config file (tailwind.config.js):<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nnpx tailwindcss init\n<\/pre><\/div>\n\n\n<p>We now need to adapt this newly created config to work with our Vite project setup:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmodule.exports = {\n content: &#x5B;\n   &#039;.\/main.js&#039;,\n   &#039;.\/index.html&#039;,\n ],\n theme: {\n   extend: {},\n },\n plugins: &#x5B;],\n}\n<\/pre><\/div>\n\n\n<p>To include Tailwind CSS, add the following lines at the top of your style.css:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n<\/pre><\/div>\n\n\n<p>Next, we need to create a config file named postcss.config.js in our root directory for postcss. We, therefore, add:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmodule.exports = {\n\tplugins: &#x5B;\n    \trequire(&#039;tailwindcss&#039;),\n    \trequire(&#039;autoprefixer&#039;)\n\t]\n}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Step 3: Starting vite<\/h3>\n\n\n\n<p>We can now start vite in dev mode to serve our files with hot reloading:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nyarn dev\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Step 4: Preparing our HTML<\/h3>\n\n\n\n<p>Next, we want to adapt the default landing page. To do so, we open the index.html and build a form. We will need the following elements:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>A wrapper for our input &lt;form id=\u201dcurrency_converter\u201d>t<\/li><li>An input for our base currency: &lt;input id=\u201dbase_currency_input\u201d><\/li><li>A base currency selection &lt;select id=\u201dcurrency\u201d><\/li><li>A submit button &lt;button type=\u201dsubmit\u201d><\/li><li>A response container &lt;div id=\u201dresult\u201d><\/li><\/ul>\n\n\n\n<p>Here is what our implementation of the index.html looks like:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;!DOCTYPE html&gt;\n&lt;html lang=&quot;en&quot;&gt;\n \n&lt;head&gt;\n &lt;meta charset=&quot;UTF-8&quot; \/&gt;\n &lt;link rel=&quot;icon&quot; type=&quot;image\/svg+xml&quot; href=&quot;favicon.svg&quot; \/&gt;\n &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; \/&gt;\n &lt;title&gt;Currency converter example&lt;\/title&gt;\n&lt;\/head&gt;\n \n&lt;body class=&quot;bg-gradient-to-b from-cyan-800 to-slate-800 min-h-screen py-5&quot;&gt;\n &lt;form id=&quot;currency_converter&quot; class=&quot;mx-auto w-full max-w-sm bg-white shadow rounded-md p-5 space-y-3 text-sm&quot;&gt;\n   &lt;div class=&quot;flex items-center space-x-5&quot;&gt;\n     &lt;label for=&quot;base_currency_input&quot;&gt;Amount:&lt;\/label&gt;\n     &lt;input type=&quot;tel&quot; id=&quot;base_currency_input&quot; name=&quot;base_currency_input&quot; placeholder=&quot;1&quot; value=&quot;&quot;\n       class=&quot;grow border-slate-300 border rounded-md py-2 px-4 text-sm&quot; required \/&gt;\n   &lt;\/div&gt;\n   &lt;div class=&quot;flex items-center space-x-5&quot;&gt;\n     &lt;label for=&quot;currency&quot;&gt;Currency:&lt;\/label&gt;\n     &lt;select name=&quot;currency&quot; id=&quot;currency&quot;\n       class=&quot;bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500&quot;&gt;\n       &lt;option selected value=&quot;USD&quot;&gt;USD&lt;\/option&gt;\n       &lt;option value=&quot;EUR&quot;&gt;EUR&lt;\/option&gt;\n       &lt;option value=&quot;CHF&quot;&gt;CHF&lt;\/option&gt;\n     &lt;\/select&gt;\n   &lt;\/div&gt;\n   &lt;button type=&quot;submit&quot; class=&quot;bg-slate-800 text-white rounded-md py-2 px-4 mx-auto relative block w-full&quot;&gt;Convert\n   &lt;\/button&gt;\n &lt;\/form&gt;\n &lt;div id=&quot;result&quot;\n   class=&quot;mx-auto my-5 w-full max-w-sm bg-white shadow rounded-md relative overflow-hidden text-sm empty:hidden divide-y divide-dotted divide-slate-300&quot;&gt;\n &lt;\/div&gt;\n &lt;script type=&quot;module&quot; src=&quot;\/main.js&quot;&gt;&lt;\/script&gt;\n&lt;\/body&gt;\n \n&lt;\/html&gt;\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Step 5: Handling the form submission in JavaScript<\/h3>\n\n\n\n<p>In our main.js, we send the currency amount (`base_currency_input`) and the currency (`base_currency`) to our backend. We will receive a list of all currencies and the corresponding values in the response.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\nimport &#039;.\/style.css&#039;\n \nconst currencyConverter = document.getElementById(&#039;currency_converter&#039;);\nconst baseCurrencyInput = document.getElementById(&#039;base_currency_input&#039;);\nconst baseCurrency = document.getElementById(&#039;currency&#039;);\nconst resultContainer = document.getElementById(&#039;result&#039;);\n \ncurrencyConverter.addEventListener(&#039;submit&#039;, (e) =&gt; {\n e.preventDefault();\n \n fetch(`http:\/\/localhost:6001\/convert?` + new URLSearchParams({ &#039;base_currency_input&#039;: baseCurrencyInput.value, &#039;currency&#039;: baseCurrency.value }))\n   .then(response =&gt; response.json())\n   .then(data =&gt; {\n     var result = &#039;&lt;div class=&quot;space-y-1 px-5 py-3 border-2 rounded-md&quot;&gt;&#039;;\n     for (let entry of data) {\n       result += `&lt;div class=&quot;flex items-baseline justify-between&quot;&gt;&lt;span class=&quot;font-medium&quot;&gt;${entry.code}:&lt;\/span&gt;&lt;span&gt;${entry.value}&lt;\/span&gt;&lt;\/div&gt;`;\n     }\n     resultContainer.innerHTML = result;\n   });\n});\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Step 6: Preparing the backend application<\/h3>\n\n\n\n<p>Now, we create a new folder, ie: `backend-application` inside the `currency-converter` folder:<\/p>\n\n\n\n<p><em>Note: The commands are valid for macOS\/Linux; for Windows, please check <\/em><a href=\"https:\/\/flask.palletsprojects.com\/en\/2.1.x\/installation\/\" target=\"_blank\" rel=\"noopener\"><em>here<\/em><\/a><em>.<\/em><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmkdir backend-application\ncd backend-application\npython3 \u2013m venv venv\n. venv\/bin\/activate\npip install Flask currencyapicom\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Step 7: Creating the backend app<\/h3>\n\n\n\n<p>In the last step, we simply add a new file called `main.py`:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom flask import Flask, request, jsonify\nfrom currencyapicom import Client\nfrom config import CURRENCYAPI_KEY\n \napp = Flask(__name__)\n \n \n@app.route(&quot;\/convert&quot;, methods=&#x5B;&#039;GET&#039;])\ndef convert():\n   currency_input = request.args.get(&#039;base_currency_input&#039;, &#039;&#039;)\n   currency = request.args.get(&#039;currency&#039;, &#039;USD&#039;)\n \n   if currency_input and currency in &#x5B;&#039;USD&#039;, &#039;EUR&#039;, &#039;CHF&#039;]:\n       api_client = Client(CURRENCYAPI_KEY)\n       response = api_client.latest(currency)\n \n       response = jsonify(&#x5B;{&#039;value&#039;: response&#x5B;&#039;data&#039;]&#x5B;x]&#x5B;&#039;value&#039;] * float(currency_input), &#039;code&#039;: x} for x in response&#x5B;&#039;data&#039;].keys()])\n       response.headers.add(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)\n \n       return response\n<\/pre><\/div>\n\n\n<p>We can run the application with a few simple commands (we bind the port to 6001 to avoid conflict with other apps):<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nexport FLASK_APP=main\nflask run \u2013port 6001\n<\/pre><\/div>\n\n\n<p>In the last step, we need to create a `config.py` file, including the currencyapi.com API key. You can get it free and learn more about the API in the <a href=\"https:\/\/currencyapi.com\/docs\" target=\"_blank\" rel=\"noopener\">documentation<\/a>.<\/p>\n\n\n\n<p>And that\u2019s it!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Up-to-date and accurate<\/h2>\n\n\n\n<p>With these few steps, you can now build your own currency converter using Python and display accurate and up-to-date prices in different currencies. There are many use cases for a currency converter; whether you use it for e-commerce stores, analytics, or spreadsheets, we hope this tutorial will guide you through the process.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Have you ever tried to offer a product, a service, or simply wanted to display prices in different currencies? Then you know how hard it can be to provide up-to-date and accurate exchange rates. This is where currency exchange APIs come in. An exchange API helps you handle your forex rate conversions. In this example, [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":31783,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-31782","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/31782","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=31782"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/31782\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/31783"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=31782"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=31782"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=31782"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}