File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Fetch the current price of a cryptocurrency in USD using CoinGecko API.
3+ """
4+
5+ import httpx
6+
7+
8+ def crypto_price (coin : str = "bitcoin" ) -> float :
9+ """
10+ Return the current price of a cryptocurrency in USD using CoinGecko API.
11+
12+ >>> isinstance(crypto_price("bitcoin"), float)
13+ True
14+ >>> isinstance(crypto_price("ethereum"), float)
15+ True
16+ """
17+ url = f"https://api.coingecko.com/api/v3/simple/price?ids={ coin } &vs_currencies=usd"
18+ try :
19+ response = httpx .get (url , timeout = 10 )
20+ response .raise_for_status ()
21+ return float (response .json ().get (coin , {}).get ("usd" , 0.0 ))
22+ except (httpx .RequestError , ValueError , KeyError ):
23+ return 0.0
24+
25+
26+ if __name__ == "__main__" :
27+ print (crypto_price ("bitcoin" ))
You can’t perform that action at this time.
0 commit comments