Skip to content

Commit a7888ea

Browse files
committed
feat: add crypto price fetcher using httpx
1 parent 68473af commit a7888ea

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
Fetch current cryptocurrency prices using the CoinGecko API.
3+
This script uses the 'httpx' library as per the repository's preference.
4+
"""
5+
6+
from __future__ import annotations
7+
import httpx
8+
9+
def fetch_crypto_price(coin_id: str = "bitcoin") -> dict[str, dict[str, float]]:
10+
"""
11+
Fetch the current price of a cryptocurrency in USD.
12+
:param coin_id: The ID of the coin (e.g., 'bitcoin', 'ethereum', 'dogecoin')
13+
:return: A dictionary containing the price data.
14+
15+
>>> # Note: Actual API call results may vary over time.
16+
>>> isinstance(fetch_crypto_price("bitcoin"), dict)
17+
True
18+
>>> "bitcoin" in fetch_crypto_price("bitcoin")
19+
True
20+
"""
21+
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
22+
23+
with httpx.Client() as client:
24+
response = client.get(url)
25+
if response.status_code != 200:
26+
raise ValueError(f"Could not fetch price for {coin_id}. Status code: {response.status_code}")
27+
28+
data = response.json()
29+
if not data:
30+
raise ValueError(f"Invalid coin ID: {coin_id}")
31+
32+
return data
33+
34+
if __name__ == "__main__":
35+
try:
36+
coin = "bitcoin"
37+
price_data = fetch_crypto_price(coin)
38+
price = price_data[coin]["usd"]
39+
print(f"The current price of {coin.capitalize()} is ${price:,.2f} USD")
40+
except Exception as e:
41+
print(f"Error: {e}")

0 commit comments

Comments
 (0)