How to Currency Converter in Python

Published on Aug. 22, 2023, 12:16 p.m.

To build a currency converter in Python, you will need to use an API that provides currency conversion rates. One popular API for this purpose is the Open Exchange Rates API. Here is an example code snippet that uses this API to convert between currencies:

import requests

# API endpoint URL
url = 'https://openexchangerates.org/api/latest.json'

# API access key
access_key = 'YOUR_ACCESS_KEY_HERE'

# base currency to convert from
base_currency = 'USD'

# target currency to convert to
target_currency = 'EUR'

# amount to convert
amount = 100.0

# make API request
response = requests.get(url, params={'app_id': access_key, 'base': base_currency})

# extract exchange rates from response
exchange_rates = response.json()['rates']

# calculate conversion rate
conversion_rate = exchange_rates[target_currency]

# calculate target amount
target_amount = amount * conversion_rate

# print result
print(f'{amount:.2f} {base_currency} = {target_amount:.2f} {target_currency}')

In this example, we first define the API endpoint URL and our access key. We then specify the base currency, target currency, and amount to convert. We make the API request using requests.get() and extract the exchange rates from the JSON response using indexing. We then calculate the conversion rate and target amount based on the exchange rates and amount to convert. Finally, we print the result.

Note that to use the Open Exchange Rates API, you will need to sign up for a free or paid account to obtain an API access key. Additionally, this example code assumes that the target currency is specified as a three-letter currency code (e.g. ‘USD’, ‘EUR’). If you need to convert between currencies using symbols (e.g. ‘$’, ‘€’), you may need to use a library or API that can perform this mapping.

Tags:

related content