Building a Currency Converter in Python

Currencyapi.com provides currency data with update rates ranging from daily to minutely update frequencies. Developer experience is important to us. Therefore, you may access our API with GET requests or alternatively use our python SDK to build a python currency converter. We will provide an example for both methods.

Using the python SDK

Using the python SDK is really the most efficient method to build a python currency converter and requires the least amount of code lines. To get started, simply install the python package with the following command:

Prerequisites

pip3 install currencyapicom

Afterwards, you will be able to access the package by entering submitting your API key to the client.

Request

import currencyapicom

client = currencyapicom.Client('YOUR-API-KEY')
result = client.latest()
print(result)

Using the requests library

Alternatively, you can directly access the API through any HTTP client. In this example, we are using python's requests library.

JSON response

import requests
url = "https://api.currencyapi.com/v3/latest"
headers = {
    'apikey': 'YOUR-API-KEY'
}
response = requests.request("GET", url, headers=headers)
print(response.text)

Both methods will lead to the same JSON response. The snippets above will provide you with a list of exchange rates relative the USD, as this is implemented as base currency. One note regarding the authentication: if you are using the requests library, please make sure to authenticate via a header parameter and not through submitting it as a GET parameter.

JSON response

{
   "meta":{
      "last_updated_at":"2023-08-02T23:59:59Z"
   },
   "data":{
      "ADA":{
         "code":"ADA",
         "value":3.3342788788
      },
      "AED":{
         "code":"AED",
         "value":3.673000426
      },
      "AFN":{
         "code":"AFN",
         "value":85.2268428169
      }
      "...": "..."
   }
}

The values in the JSON response are exchange rates. Since we intend to build a currency converter, we still have to multiply the exchange rate with the amount that we would like to convert, to end up with the desired result.

Converter Endpoint

If you do not wish to take this small extra step, currencyapi.com provides an extra /convert endpoint that was specifically designed for this task. However, it is only available for plans >= medium.