Example of using the online exchange rate conversion API in Python

Photo by Jess Bailey on Unsplash

Example of using the online exchange rate conversion API in Python

·

1 min read

Register an account on the API site

  1. First, you need to create a free account on abstractapi.com.

    image

  2. Click Exchange rates on the left menu, and get your free API key on the right side.

    image

Python Coding

Use Python to call the API and get the result of the exchange rate conversion.

import urllib.request
import json
import sys
import ssl

# the rest API source URL
base="EUR"
target="CNY"
key="your key"
url = "https://exchange-rates.abstractapi.com/v1/live/?api_key="+key+"&base="+base+"&target="+target
request = urllib.request.Request(url)

try:
    #https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-failed-error
    #gcontext = ssl.SSLContext() 
    context = ssl._create_unverified_context()
    # open the rest URL
    restUrl = urllib.request.urlopen(request,context=context)
    if (restUrl.getcode() == 200):
        # read data
        data = restUrl.read()
        # string to dictionary
        theJSON = json.loads(data)
        # print out the result
        # print(theJSON)
        print(theJSON["exchange_rates"]["CNY"])

    else:
        print('Something went wrong with the server, no results found: ' + str(restUrl.getcode()))
except:
        print(f'ERROR: {sys.exc_info()}')

When you run the program, the result will look like this

Resolved Issues

During development, we get HTTPS request SSL errors, like this

Refer to this link to solve

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

    context = ssl._create_unverified_context()
    # open the rest URL
    restUrl = urllib.request.urlopen(request,context=context)