Live Currency Rates Using Our Python SDK

Ready to enhance your Python projects? Our Python SDK for CurrencyApi.net is designed to simplify your integration process. Whether you're building web applications, data analysis tools, or server-side solutions, our SDK provides the tools you need to seamlessly incorporate live currency rates into your Python projects. Stick with us, and you'll be leveraging real-time currency data like a pro!

Installation

To get started with the CurrencyApi.net Python SDK, ensure you have Python 3.5 or higher installed. You can install the SDK using pip:

pip install currencyapinet

Importing the PHP SDK

After installation, import the SDK into your Python project:

from currencyapinet.currency import Currency

Instantiating the Python SDK Currency Class

You are now ready to start using the CurrencyApi.net Python SDK. To get started, create an instance of the Currency class by passing in your API key:

currency = Currency('YOUR_API_KEY')

Need a Currency API Key?

Access live exchange rates instantly with our Currency API. We offer free pricing plans to get you started. Sign up today and continue the Python tutorial!

Get Your Free API Key »

Fetching Live Currency Rates With Python

Now the fun part begins. Let's retrieve live currency rates with the following method:

result = currency.rates().get()

This will return a JSON response containing all the live currency rates.

The rates() method is a convenience method that returns the /rates endpoint.

Let's put it all together and look at the api response:

from currencyapinet.currency import Currency

currency = Currency('YOUR_API_KEY')
result = currency.rates().get()
print(result)
# Outputs
{
   'valid': True,
   'updated': 1727622003,
   'base': 'USD',
   'rates': {
       'AED': 3.673,
       'AFN': 68,
       'ALL': 88.25,
       'AMD': 387.32,
       'ANG': 1.801995,
       'AOA': 943.5,
       'ARS': 965.4662
       .....

Congratulations! You have successfully fetched live currency rates using our Python SDK.

Available Methods For Rates Endpoint

Method Description
base() Sets the base currency for conversions. This will output all currency conversions for that currency. Default is USD.
output() Specifies the response format: JSON or XML. Default is JSON.

Converting Currency Amounts

With our Currency API and the Python SDK its easy to convert amounts from one currency to another. This returns a smaller response size and is a great way to get the most out of our API.

The convert() method uses the /convert endpoint of our Currency API.

Let's dive in and convert 100 USD to EUR using the Python SDK:

from currencyapinet.currency import Currency

currency = Currency('YOUR_API_KEY')
result = currency.convert().from_currency('USD').to_currency('EUR').amount(100).get()
print(result)
# Outputs
{
    'valid': True,
    'updated': 1727625603,
    'conversion': {
        'amount': 10,
        'from': 'GBP',
        'to': 'USD',
        'result': 13.3710003326705
    }
}

As you can see, the response is much smaller and contains only the information you requested.

Available Methods For Convert Endpoint

Method Description
from_currency() The currency you want to convert. This will be a three letter ISO 4217 currency code from one of the currencies we have rates for. Required.
to_currency() The currency you want to convert the amount 'to'. Again this will be a three letter currency code from the ones we offer. Required.
amount() The value of the currency you want to convert from. This should be a number and can contain a decimal place. Required.
output() Specifies the response format: JSON or XML. Default is JSON.

Fetching Historical Currency Rates Using Python

Sometimes you need to access historical currency rates. We have a range of endpoints to help you do just that.

The history() method uses the /history endpoint of our Currency API.

Let's retrieve historical currency rates for the USD base currency on January 1st, 2019 using the Python SDK:

from currencyapinet.currency import Currency

currency = Currency('YOUR_API_KEY')
result = currency.history().date('2019-01-01').base('USD').output('JSON').get()
print(result)
# Outputs
{
    'valid': True,
    'base': 'USD',
    'date': '2019-01-01',
    'rates': {
        'AED': 3.673105,
        'AFN': 75.615,
        'ALL': 107.726773,
        'AMD': 484.068111,
        'ANG': 1.770652,
        'AOA': 308.607,
        'ARS': 37.6515
        .....

The API response returns a JSON object containing historical currency rates for the day you requested.

Available Methods For History Endpoint

Method Description
date() The historical date you wish to receive the currency conversions for. This should be formatted as YYYY-MM-DD. Required
base() Sets the base currency for conversions. This will output all currency conversions for that currency. Default is USD.
output() Specifies the response format: JSON or XML. Default is JSON.

Use Python SDK To Access Rates Within A Timeframe

Accessing currency rates within a timeframe allows developer to build applications that track currency rates over time. Think graphs, charts, or any other application that requires real-time currency data.

The method timeframe() is a helper method that uses the /timeframe endpoint of our Currency API.

Using this method, we can return multiple days in a single response. Let's retrieve the rates for the USD base currency between January 1st, 2019 and January 1st, 2020 using the Python SDK:

from currencyapinet.currency import Currency

currency = Currency('YOUR_API_KEY')
result = currency.timeframe().start_date('2019-01-01').end_date('2019-01-01').get()
print(result)
# Outputs
{
    'valid': True,
    'base': 'USD',
    'start_date': '2019-01-01',
    'end_date': '2019-01-02',
    'rates': {
        '2019-01-01': {
            'AED': 3.673105,
            'AFN': 75.615,
            'ALL': 107.726773,
            'AMD': 484.068111,
            'ANG': 1.770652,
            'AOA': 308.607,
            'ARS': 37.6515
            .....
        },
        '2019-01-02': {
            'AED': 3.673105,
            'AFN': 75.615,
            'ALL': 107.726773,
            'AMD': 484.068111,
            'ANG': 1.770652,
            'AOA': 308.607,
            'ARS': 37.6515
            ....
        }

The API returns multiple days of currency rates in a single response, making it easy to build applications that track currency rates over time.

Available Methods For Timeframe Endpoint

Method Description
start_date() The historical date you wish to receive the currency conversions from. This should be formatted as YYYY-MM-DD. Required
end_date() The historical date you wish to receive the currency conversions until. This should be formatted as YYYY-MM-DD. Required
base() Sets the base currency for conversions. This will output all currency conversions for that currency. Default is USD.
output() Specifies the response format: JSON or XML. Default is JSON.

Best Practices

When using the Python SDK, follow these best practices to ensure efficient and reliable integration:

  • Cache responses when possible to reduce API calls and improve performance.
  • Handle exceptions to prevent your application from crashing due to unexpected errors.
  • Use environment variables to store your API key securely.
  • Refer to the official documentation for advanced usage and updates.

Handling Responses

JSON Response

The SDK returns responses in your specified format. By default, the API will return a JSON response. Therefore, you do not need to specify any output to return a JSON response.

XML Response

You can specify the output by using the output parameter. This can be set to either JSON or XML. Let's have a look how to output XML below:

result = currency.rates().output('XML').get()
print(result)
# Outputs
<?xml version="1.0" encoding="utf-8"?>
<root><valid>true</valid>
<updated>1727720883</updated>
<base>USD</base>
<rates>
    <AED>3.673</AED>
    <AFN>68</AFN>
    <ALL>88.25</ALL>
    <AMD>387.29</AMD>
    <ANG>1.80184</ANG>
    <AOA>943</AOA>
    <ARS>968.7457</ARS>
    ...

Then in Python, you can handle the XML response using the xml.etree.ElementTree module:

from currencyapinet.currency import Currency
from xml.etree import ElementTree

currency = Currency('YOUR_API_KEY')
result = currency.rates().output('XML').get()
root = ElementTree.fromstring(result)
rates_element = root.find("rates")

for currency in rates_element:
    print(f"Currency: {currency.tag}, Rate: {currency.text}")
# Outputs
Currency: AED, Rate: 3.673
Currency: AFN, Rate: 69
Currency: ALL, Rate: 89.675
Currency: AMD, Rate: 386.99
...

Looping Over The Response in JSON using Python

To loop over the JSON response in your Python code

result = currency.rates().get()
base_currency = result['base']
rates = result['rates']
print(f"Base Currency: {base_currency}")
for currency, rate in rates.items():
    print(f"{currency}: {rate}")
# Outputs
Base Currency: USD
AED: 3.673
AFN: 68
ALL: 88.25
AMD: 387.29
ANG: 1.80184
AOA: 943
ARS: 968.7109

Error Handling - Python SDK

In Python, we use the exception type to handle errors. This allows us to gracefully handle errors and provide meaningful error messages to the user.

In doing this, we can handle exceptions and errors gracefully to ensure our application remains robust:

try:
    result = currency.rates().get()
except Exception as e:
    print(f"An error occurred: {e}")

Integrating into Your Python / Django / Flask Application

In this section, we will look at how to integrate the CurrencyApi.net Python SDK into your Python / Django / Flask application.

We will be using the Currency class and the convert method to convert currencies.

from currencyapinet.currency import Currency

def convert_currency(amount, from_currency, to_currency):
    result = currency.convert().from_currency(from_currency).to_currency(to_currency).amount(amount).get()
    return result['conversion']['result']

currency = Currency('YOUR_API_KEY')
try:
    converted = convert_currency(100, 'BTC', 'USD')
    print(f"100 BTC is equal to {converted} USD")
except Exception as e:
    print(f"An error occurred: {e}")

Conclusion

Our Python SDK for CurrencyApi.net provides a straightforward and efficient way to integrate live currency rates into your Python applications. With easy installation, comprehensive documentation, and reliable support, you can enhance your projects with up-to-date currency data seamlessly.

Other Useful Links:

Other SDKs

Not using Python? Try out one of our other SDK's below.

GoLang SDK

Quickly implement currency data into your GoLang applications with our user-friendly SDK. Access live exchange rates, currency conversions, and more.

Explore the GoLang SDK →

NodeJs SDK

Integrate real-time currency services into your NodeJs projects. Our SDK provides you with powerful tools for handling currency data with minimal effort.

Discover the NodeJs SDK →

PHP SDK

Seamlessly connect to our Currency API from your PHP applications. This SDK ensures smooth and efficient access to the latest currency rates and services.

Check out the PHP SDK →

Get Started with CurrencyApi.net Today!

Sign up now to access live currency rates and enhance your Python applications.

View Pricing & Plans »
Meet the Author
Oli Girling

Oli Girling

Founder & Senior Software Engineer

London, UK

Connect on LinkedIn