Table of Contents
Table of Contents
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!
Getting Started with the Python SDK
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
Installing the Python SDK
After installation, import the SDK into your Python project:
from currencyapinet.currency import Currency
Creating Your Python SDK Instance
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')
Have you got an API key?
It's super easy to get started with our Python SDK. Signup for a free API key and start building your next project.
Retrieving Live Rates in 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)
Congratulations! You have successfully fetched live currency rates using our Python SDK.
Available Methods for Rates Endpoint with Python SDK
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. |
Currency Conversion with Python SDK
With our Currency API and the Python SDK it's 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)
As you can see, the response is much smaller and contains only the information you requested.
Available Python SDK 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. |
Accessing Historical Currency Rates in 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)
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 developers 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)
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 for Python Integration
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()
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}")
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}")
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:
Explore Other SDKs
Not using Python? Try out one of our other SDKs 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.
Meet the Author
