Skip to content
Closed
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
47 changes: 47 additions & 0 deletions web_programming/fetch_crypto_prices.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Fetch current cryptocurrency prices using the CoinGecko API.
This script uses the 'httpx' library as per the repository's preference.
"""

from __future__ import annotations
import httpx

Check failure on line 7 in web_programming/fetch_crypto_prices.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (I001)

web_programming/fetch_crypto_prices.py:6:1: I001 Import block is un-sorted or un-formatted help: Organize imports


def fetch_crypto_price(coin_id: str = "bitcoin") -> dict[str, dict[str, float]]:
"""
Fetch the current price of a cryptocurrency in USD.
:param coin_id: The ID of the coin (e.g., 'bitcoin', 'ethereum', 'dogecoin')
:return: A dictionary containing the price data.

>>> # Note: Actual API call results may vary over time.
>>> isinstance(fetch_crypto_price("bitcoin"), dict)
True
>>> "bitcoin" in fetch_crypto_price("bitcoin")
True
"""
url = (
f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=usd"
)

with httpx.Client() as client:
response = client.get(url)
if response.status_code != 200:
raise ValueError(
f"Could not fetch price for {coin_id}. Status code: {response.status_code}"

Check failure on line 30 in web_programming/fetch_crypto_prices.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (E501)

web_programming/fetch_crypto_prices.py:30:89: E501 Line too long (91 > 88)

Check failure on line 30 in web_programming/fetch_crypto_prices.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (EM102)

web_programming/fetch_crypto_prices.py:30:17: EM102 Exception must not use an f-string literal, assign to variable first help: Assign to variable; remove f-string literal
)

data = response.json()
if not data:
raise ValueError(f"Invalid coin ID: {coin_id}")

Check failure on line 35 in web_programming/fetch_crypto_prices.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (EM102)

web_programming/fetch_crypto_prices.py:35:30: EM102 Exception must not use an f-string literal, assign to variable first help: Assign to variable; remove f-string literal

return data


if __name__ == "__main__":
try:
coin = "bitcoin"
price_data = fetch_crypto_price(coin)
price = price_data[coin]["usd"]
print(f"The current price of {coin.capitalize()} is ${price:,.2f} USD")
except Exception as e:

Check failure on line 46 in web_programming/fetch_crypto_prices.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (BLE001)

web_programming/fetch_crypto_prices.py:46:12: BLE001 Do not catch blind exception: `Exception`
print(f"Error: {e}")
Loading