SharedClass Samples / currency-exchange-api / currency_exchange.pyOpen in CoCalc
Authors: Barry Bandstra, Marissa Doshi, Ryan McFall
1
import requests
2
import json
3
4
baseUrl = 'http://apilayer.net/api/'
5
6
# Read the key
7
with open("access_key.txt") as keyfile:
8
key = keyfile.readline().strip()
9
10
# Load the list of available currencies
11
listUrl = baseUrl + 'list'
12
response = requests.get(listUrl, params={'access_key': key, })
13
# Convert the response into a Python dictionary
14
# The 'Types' chapter in the book describes dictionaries
15
currency_dictionary = json.loads(response.content)['currencies']
16
17
# Print them all out (for now, this could be better later!)
18
for code in sorted(currency_dictionary.keys()):
19
# The encoding stuff here is because the currency names have
20
# Unicode characters that can't be printed
21
print code, currency_dictionary[code].encode('ascii', 'ignore')
22
23
# Ask the user for an amount in dollars to convert
24
amount = float(raw_input('How much money do you want to convert? '))
25
26
# Ask the user for the code for the country they want
27
country_code = raw_input('Enter code for the country you want: ')
28
29
# Request the current exchange rate for that country
30
quoteUrl = baseUrl + 'live'
31
32
response = requests.get(quoteUrl, params={'access_key': key, 'currencies': country_code})
33
34
rate = json.loads(response.content)['quotes']['USD' + country_code]
35
36
print amount, 'American dollars is', amount*rate, currency_dictionary[country_code]
37
38
39