Skip to content

Python Example Code

MMDRZA edited this page Oct 18, 2024 · 2 revisions

Fetching and Displaying Cryptocurrency Data from a JSON API

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.

Python Example Code

The following code fetches the JSON data from the provided URL and displays the relevant coin information in a readable format.

importrequestsimportjson# URL of the raw JSON fileRAW_JSON_URL="https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json"deffetch_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 errorsreturnresponse.json() exceptrequests.exceptions.HTTPErrorashttp_err: raiseException(f"HTTP error occurred: {http_err}") exceptrequests.exceptions.RequestExceptionasreq_err: raiseException(f"Request error occurred: {req_err}") exceptjson.JSONDecodeErrorasjson_err: raiseException(f"JSON decoding error: {json_err}") defdisplay_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 informationprint(f"Symbol: {coin_symbol} | LAST: {last_price} | "f"HIGH: {high_price_24h} | LOW: {low_price_24h} | "f"CHANGE: {change_rate} | UPDATED: {last_updated}") exceptKeyErrorase: raiseException(f"Missing expected key in data: {e}") if__name__=="__main__": try: # Fetch the JSON datacoin_data_list=fetch_json_data(RAW_JSON_URL) # Loop through the data and display information for each coinforcoinincoin_data_list: display_coin_info(coin) exceptExceptionase: print(f"Error: {e}")

How It Works

  • 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.

Error Handling

  • 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.

How to Use

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

Clone this wiki locally