migrate to git.charlotte.sh
This commit is contained in:
commit
fbd588721e
412 changed files with 13750 additions and 0 deletions
48
python-csi160/json-api-lab/main.py
Normal file
48
python-csi160/json-api-lab/main.py
Normal file
|
@ -0,0 +1,48 @@
|
|||
# 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")
|
1
python-csi160/json-api-lab/requirements.txt
Normal file
1
python-csi160/json-api-lab/requirements.txt
Normal file
|
@ -0,0 +1 @@
|
|||
requests
|
Loading…
Add table
Add a link
Reference in a new issue