Python Snippets

Real-time Currency Converter with API Integration

import requests
import json
from typing import Dict, Optional

class CurrencyConverter:
    def __init__(self, api_key: str = None):
        """
        Initialize the currency converter with optional API key.
        Uses exchangerate-api.com as the default service.
        """
        self.api_key = api_key
        self.base_url = "https://api.exchangerate-api.com/v4/latest/"
        self.rates_cache = {}
    
    def get_exchange_rates(self, base_currency: str = "USD") -> Optional[Dict]:
        """
        Fetch current exchange rates for a base currency.
        Uses caching to avoid repeated API calls.
        """
        if base_currency in self.rates_cache:
            return self.rates_cache[base_currency]
        
        try:
            url = f"{self.base_url}{base_currency}"
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            self.rates_cache[base_currency] = data['rates']
            return data['rates']
        except requests.RequestException as e:
            print(f"Error fetching exchange rates: {e}")
            return None
        except KeyError:
            print("Invalid response format from API")
            return None
    
    def convert(self, amount: float, from_currency: str, to_currency: str) -> Optional[float]:
        """
        Convert amount from one currency to another.
        Returns None if conversion fails.
        """
        # Normalize currency codes to uppercase
        from_currency = from_currency.upper()
        to_currency = to_currency.upper()
        
        # Get exchange rates with USD as base
        rates = self.get_exchange_rates("USD")
        if not rates:
            return None
        
        try:
            # Convert to USD first, then to target currency
            # This handles any currency pair even if direct rates aren't available
            usd_amount = amount / rates[from_currency]
            converted_amount = usd_amount * rates[to_currency]
            return round(converted_amount, 2)
        except KeyError as e:
            print(f"Currency not supported: {e}")
            return None
        except ZeroDivisionError:
            print("Error: Division by zero in conversion")
            return None

# Example usage
if __name__ == "__main__":
    converter = CurrencyConverter()
    
    # Convert 100 USD to EUR
    result = converter.convert(100, "USD", "EUR")
    if result:
        print(f"100 USD = {result} EUR")
    
    # Convert 50 EUR to JPY
    result = converter.convert(50, "EUR", "JPY")
    if result:
        print(f"50 EUR = {result} JPY")
    
    # Convert 1000 INR to USD
    result = converter.convert(1000, "INR", "USD")
    if result:
        print(f"1000 INR = {result} USD")

What This Code Does

This is a real-time currency converter that fetches current exchange rates from a free API and performs currency conversions between any supported currencies. The converter uses caching to minimize API calls and improve performance.

Key Features

Why This is Useful

Currency conversion is a common requirement in financial applications, e-commerce platforms, travel apps, and international business software. This snippet provides a production-ready solution that handles:

  1. Network reliability issues
  2. Data caching for better performance
  3. Error recovery when APIs fail
  4. Support for 160+ currencies
  5. Clean, maintainable code structure

How to Run

  1. Install Requirements:
    pip install requests
    
  2. Run the Code: Save as currency_converter.py and execute:
    python currency_converter.py
    
  3. Use in Your Projects:
    from currency_converter import CurrencyConverter
       
    converter = CurrencyConverter()
    usd_to_eur = converter.convert(100, "USD", "EUR")
    print(f"${100} = €{usd_to_eur}")
    

Customization Options

The converter is limited to free API calls (about 1500/month) from exchangerate-api.com. For production use, consider getting an API key and using their commercial endpoints.