Skip to content

Instantly share code, notes, and snippets.

@PiotrCzapla
Last active March 16, 2022 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PiotrCzapla/074d8e73c6c12a66869918187e49b84d to your computer and use it in GitHub Desktop.
Save PiotrCzapla/074d8e73c6c12a66869918187e49b84d to your computer and use it in GitHub Desktop.
Get NBP currency exchange rate in python with memory cache, this can act as simple python API :)
# license: mit
import requests
from functools import lru_cache
@lru_cache(maxsize=None)
def get_nbp_exchange_rate(date:datetime, table='A'):
"""
Get the exchange rate from the NBP API, and store it in cache folder
>> get_nbp_exchange_rate(datetime(2022,3,8))['EUR']
4.9121
"""
url = 'http://api.nbp.pl/api/exchangerates/tables/{:s}/{:%Y-%m-%d}/?format=json'.format(table, date)
r = requests.get(url)
if r.status_code != 200:
raise RuntimeError("Unable to fetch exchange rate from NBP API")
return {rate['code']:rate['mid'] for rate in r.json()[0]['rates']}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment