1
+ import requests
2
+ import urllib .parse as p
3
+
4
+ API_KEY = "vh2Fth1cu2oe3AFJV5CtTgz50tgjUGUOhlHx0jrk"
5
+ base_url = "https://api.currencyapi.com/v3/"
6
+
7
+ # utility function that both functions will use
8
+ def get_currencyapi_data (endpoint , date = None , base_currency = "USD" , print_all = True ):
9
+ """Get the list of currency codes from the API"""
10
+ # construct the url
11
+ url = p .urljoin (base_url ,
12
+ f"{ endpoint } ?apikey={ API_KEY } { '' if endpoint == 'latest' else f'&date={ date } ' } &base_currency={ base_currency } " )
13
+ # make the request
14
+ res = requests .get (url )
15
+ # get the json data
16
+ data = res .json ()
17
+ # print all the currency codes and their values
18
+ c = 0
19
+ if print_all :
20
+ for currency_code , currency_name in data .get ("data" ).items ():
21
+ print (f"{ currency_code } : { currency_name .get ('value' )} " )
22
+ c += 1
23
+
24
+ print (f"Total: { c } currencies" )
25
+ if endpoint == "latest" :
26
+ # get the last updated date
27
+ last_updated = data .get ("meta" ).get ("last_updated_at" )
28
+ print (f"Last updated: { last_updated } " )
29
+ return data
30
+
31
+ def get_latest_rates (base_currency = "USD" , print_all = True ):
32
+ """Get the latest rates from the API"""
33
+ return get_currencyapi_data (endpoint = "latest" , base_currency = base_currency , print_all = print_all )
34
+
35
+ def get_historical_rates (base_currency = "USD" , print_all = True , date = "2023-01-01" ):
36
+ """Get the historical rates from the Currency API
37
+ `date` must be in the format of YYYY-MM-DD"""
38
+ return get_currencyapi_data (endpoint = "historical" , base_currency = base_currency , date = date , print_all = print_all )
39
+
40
+
41
+ if __name__ == "__main__" :
42
+ latest_rates = get_latest_rates ()
43
+ print (f"\n { '-' * 50 } \n " )
44
+ # get the historical rates for the date 2021-01-01
45
+ historical_rates = get_historical_rates (date = "2021-01-01" , print_all = False )
46
+ # get EUR rate, for example
47
+ eur_rate = historical_rates .get ("data" ).get ("EUR" ).get ("value" )
48
+ print (f"EUR rate on 2021-01-01: { eur_rate } " )
0 commit comments