Building a Currency Converter in Python Using APIs

·

Introduction to Currency Conversion with APIs

This tutorial guides you through creating a practical currency converter using Python and APIs. It's designed for beginners looking to gain hands-on experience with real-world API integration.

Key Features of This Project

Step-by-Step Implementation

Step 1: Obtaining Your API Key

To begin, you'll need an API key from a currency exchange service. We recommend:

👉 Open Exchange Rates API
(Free tier available with registration)

Important Security Note: Always keep your API key confidential. Never commit it to version control or share it publicly.

Step 2: Environment Setup

Required Python packages:

import argparse
from typing import Optional
import requests

Step 3: Fetching Exchange Rates

Here's our core function for retrieving exchange rates:

def fetch_usd_exchange_rate(api_url: str, target_currency: str) -> Optional[float]:
    """Fetch USD exchange rate for target currency"""
    try:
        response = requests.get(api_url, timeout=120)
        response.raise_for_status()
        rates = response.json().get("rates", {})
        return rates.get(target_currency, None)
    except requests.RequestException as exception:
        print(f"Failed to fetch exchange rates: {exception}")
        return None

This function includes:

Step 4: Currency Conversion Logic

The conversion function builds on our rate fetcher:

def convert_currency(api_url: str, amount: float, target_currency: str) -> Optional[float]:
    """Convert USD amount to target currency"""
    rate = fetch_usd_exchange_rate(api_url, target_currency)
    return amount * rate if rate is not None else None

Step 5: User Interface Implementation

Our main function creates an interactive CLI:

def main(api_url: str) -> None:
    while True:
        target_currency = input("Convert USD to currency (Type 'exit' to quit): ")
        if target_currency.lower() == "exit":
            break
        try:
            amount = float(input("Amount in USD: "))
            target_amount = convert_currency(api_url, amount, target_currency)
            if target_amount:
                print(f"{amount} USD = {target_amount} {target_currency}")
            else:
                print("Conversion failed. Check currency code and try again.")
        except ValueError:
            print("Please enter a valid numeric amount")

Complete Project Code

import argparse
from typing import Optional
import requests

def fetch_usd_exchange_rate(api_url: str, target_currency: str) -> Optional[float]:
    """Fetch USD exchange rate for target currency"""
    try:
        response = requests.get(api_url, timeout=120)
        response.raise_for_status()
        rates = response.json().get("rates", {})
        return rates.get(target_currency, None)
    except requests.RequestException as exception:
        print(f"Failed to fetch exchange rates: {exception}")
        return None

def convert_currency(api_url: str, amount: float, target_currency: str) -> Optional[float]:
    """Convert USD amount to target currency"""
    rate = fetch_usd_exchange_rate(api_url, target_currency)
    return amount * rate if rate is not None else None

def main(api_url: str) -> None:
    while True:
        target_currency = input("Convert USD to currency (Type 'exit' to quit): ")
        if target_currency.lower() == "exit":
            break
        try:
            amount = float(input("Amount in USD: "))
            target_amount = convert_currency(api_url, amount, target_currency)
            if target_amount:
                print(f"{amount} USD = {target_amount} {target_currency}")
            else:
                print("Conversion failed. Check currency code and try again.")
        except ValueError:
            print("Please enter a valid numeric amount")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Currency Converter")
    parser.add_argument("api_url", type=str, help="API URL including key")
    args = parser.parse_args()
    main(args.api_url)

Testing Your Converter

Example usage:

python currency_converter.py "https://openexchangerates.org/api/latest.json?app_id=YOUR_API_KEY"

Sample interaction:

Convert USD to currency (Type 'exit' to quit): EUR
Amount in USD: 100
100.0 USD = 85.50 EUR

Frequently Asked Questions

What are the best free currency APIs?

👉 Top currency API providers offer free tiers suitable for small projects and testing.

How often are exchange rates updated?

Most commercial APIs update rates every 60 minutes, while premium services may offer real-time updates.

Can I convert between non-USD currencies?

Yes, by first converting to USD, then to your target currency (known as cross-rates).

What's the best way to secure my API key?

Why is my conversion returning None?

Common causes:

Advanced Enhancements

Consider adding:

Conclusion

This project demonstrates Python's power for financial applications and API integration. The skills learned translate to many other API-based projects.

For more financial programming resources:
👉 Advanced API integration tutorials

Would you like me to expand on any particular aspect of this implementation?