ChamplainTechJournals/python-csi160/json-api-lab/main.py
2025-04-19 23:42:08 -04:00

48 lines
1.6 KiB
Python

# 4/4/2025 - Charlotte Croce
# JSON API LAB
#
# this program uses the Coinbase API to get a dictionary of currencies and their prices
# the user can search for a currency by symbol and get its name and price
#
import requests
API_URL = "https://api.coinbase.com/v2/currencies"
response = requests.get(API_URL)
# Parse the JSON response
response_data = response.json()
# create dictionary with currency symbol as key and name as value
currency_dict = {currency['id']: currency['name'] for currency in response_data['data']}
# not included in the dictionary because it is many seperate requests
# and takes a while to process
def get_currency_price(symbol):
price_url = f"https://api.coinbase.com/v2/prices/{symbol}-USD/spot"
try:
price_response = requests.get(price_url)
price_data = price_response.json()
return price_data['data']['amount']
except (requests.exceptions.RequestException, KeyError, ValueError):
return "Price unavailable"
def display_list():
# ':<10' creates a 10 character wide column
print(f"{'Symbol':<10} {'Name':<10}")
for symbol, name in currency_dict.items():
print(f"{symbol:<10} {name:<10}")
while True:
# Prompt user for currency symbol
symbol = input("Enter currency symbol ('l' to list currencies')('q' to quit): ").upper()
if symbol == 'Q':
break
# if user enter's 'l' Display currencies as table
if symbol == 'L':
display_list()
# Check if symbol is in dictionary
if symbol in currency_dict:
print(f"\n{currency_dict[symbol]}\n1{symbol} = ${get_currency_price(symbol)}USD\n")
else:
print(f"{symbol} not found")