-
Notifications
You must be signed in to change notification settings - Fork 0
Python Example Code
This section demonstrates how to fetch and display cryptocurrency data from a remote JSON file using Python. The example below retrieves information such as symbol, last price, 24-hour high and low prices, change rate, and last updated timestamp for various coins. The data source is provided in the form of a raw JSON file hosted on GitHub.
The following code fetches the JSON data from the provided URL and displays the relevant coin information in a readable format.
import requests
import json
# URL of the raw JSON file
RAW_JSON_URL = "https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json"
def fetch_json_data(url: str) -> dict:
"""
Fetch JSON data from a given URL.
:param url: The URL of the JSON resource.
:return: A dictionary containing the JSON data.
:raises Exception: If the request fails or the data is invalid.
"""
try:
response = requests.get(url)
response.raise_for_status() # Raises an exception for HTTP errors
return response.json()
except requests.exceptions.HTTPError as http_err:
raise Exception(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as req_err:
raise Exception(f"Request error occurred: {req_err}")
except json.JSONDecodeError as json_err:
raise Exception(f"JSON decoding error: {json_err}")
def display_coin_info(coin_data: dict) -> None:
"""
Display information about a cryptocurrency coin.
:param coin_data: A dictionary containing information about a coin.
"""
try:
coin_symbol = coin_data["symbol"]
last_price = coin_data["lastPrice"]
high_price_24h = coin_data["highPrice24h"]
low_price_24h = coin_data["lowPrice24h"]
change_rate = coin_data["changeRate"]
last_updated = coin_data["lastUpdated"]
# Print the formatted information
print(f"Symbol: {coin_symbol} | LAST: {last_price} | "
f"HIGH: {high_price_24h} | LOW: {low_price_24h} | "
f"CHANGE: {change_rate} | UPDATED: {last_updated}")
except KeyError as e:
raise Exception(f"Missing expected key in data: {e}")
if __name__ == "__main__":
try:
# Fetch the JSON data
coin_data_list = fetch_json_data(RAW_JSON_URL)
# Loop through the data and display information for each coin
for coin in coin_data_list:
display_coin_info(coin)
except Exception as e:
print(f"Error: {e}")
-
Fetching Data: The
fetch_json_data
function retrieves the JSON data from the specified URL using Python's requests library. It ensures that the request is successful by checking the status code and raising exceptions for HTTP or request errors. -
Displaying Coin Information: The
display_coin_info
function takes a dictionary containing data about a specific cryptocurrency (e.g.,symbol
,prices
,change rate
) and prints it in a readable format. It uses exception handling to ensure the program doesn't crash if a key is missing from the data. -
Main Execution: The script fetches the entire JSON dataset, iterates through each coin's data, and calls the
display_coin_info
function to output the details of each coin.
-
HTTP Errors: The code raises an exception if the request fails due to connectivity issues, invalid URLs, or server-side errors (such as 404 or 500 errors).
-
JSON Parsing Errors: If the JSON data is malformed or cannot be decoded, the program will raise a descriptive error.
-
Missing Keys: If any expected key is missing from the JSON response, the program will raise an error indicating which key was not found.
Install Required Libraries: Make sure you have the requests library installed. You can install it using pip:
pip install requests
Run the Code: To use the script, simply run it in a Python environment. It will automatically fetch the data and print the results:
python fetch_crypto_data.py
Feel free to contribute to this project by providing feedback, submitting issues, or offering pull requests to improve the code and its functionality
👨💻 Programmer : PyMmdrza 🌍 Official Website Mmdrza.Com 📧 Email : [email protected]
📧 [email protected]