Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions web_programming/crypto_price_tracker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
Fetch the current price of a cryptocurrency in USD using CoinGecko API.
"""

import httpx


def crypto_price(coin: str = "bitcoin") -> float:
"""
Return the current price of a cryptocurrency in USD using CoinGecko API.
>>> isinstance(crypto_price("bitcoin"), float)
True
>>> isinstance(crypto_price("ethereum"), float)
True
"""
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd"
try:
response = httpx.get(url, timeout=10)
response.raise_for_status()
return float(response.json().get(coin, {}).get("usd", 0.0))
except (httpx.RequestError, ValueError, KeyError):
return 0.0


if __name__ == "__main__":
print(crypto_price("bitcoin"))