Last modified: Jul 01, 2023 By Alexander Williams

Build a Live Currency Converter in Python

In this guide, we'll build a simple live currency converter using Python and API.

Technologies

In this guide, we'll need the following library:

  • requests

requests is a library that is used for making HTTP requests. We'll use it to make an HTTP GET request to the ExchangeRate-API to fetch the latest exchange rates.

You can install the requests library using the following command:

pip install requests

Build Currency Converter

To build a live currency converter, we'll use ExchangeRate-API. This API is a web service that provides currency exchange rate data.

Here is our Currency Converter function:

import requests

def convert_currency(amount, from_currency, to_currency):
    base_url = "https://api.exchangerate-api.com/v4/latest/"

    # Fetch latest exchange rates
    response = requests.get(base_url + from_currency)
    data = response.json()

    if 'rates' in data:
        rates = data['rates']
        if from_currency == to_currency:
            return amount

        if from_currency in rates and to_currency in rates:
            conversion_rate = rates[to_currency] / rates[from_currency]
            converted_amount = amount * conversion_rate
            return converted_amount
        else:
            raise ValueError("Invalid currency!")
    else:
        raise ValueError("Unable to fetch exchange rates!")

The convert_currency function has the following parameters:

  1. amount: The amount of currency that you want to convert.
  2. from_currency: The currency you want to convert from.
  3. to_currency: The currency you want to convert to.

Now let's see how to use the function.

# Convert 100 USD to EUR (live rates)
amount = 100
from_currency = "USD"
to_currency = "EUR"
converted_amount = convert_currency(amount, from_currency, to_currency)
print(f"{amount} {from_currency} is equal to {converted_amount} {to_currency}")

Output:

100 USD is equal to 91.7 EUR

As demonstrated, we have converted 100 USD to EUR and obtained the above output.

Conclusion

In conclusion, we have learned how to build a simple live currency converter using Python and the ExchangeRate-API.

This converter lets us easily convert between currencies based on real-time exchange rates. 

If you are interested in getting the currency of any country, visit How to Get The Currency of any Country in Python.