How to Retrieve Real-Time Crypto Prices in Python?

Estimated read time 2 min read

To retrieve real-time crypto prices in Python, you can use various APIs that provide cryptocurrency data. One popular API for this purpose is the CoinGecko API. Here’s an example of how you can use the CoinGecko API to retrieve real-time crypto prices:

import requests

# Set the base API URL
base_url = ""

# Define the cryptocurrency symbol you want to retrieve the price for
crypto_symbol = "bitcoin"

# Construct the API endpoint URL
endpoint = f"{base_url}/simple/price?ids={crypto_symbol}&vs_currencies=usd"

# Send a GET request to the API
response = requests.get(endpoint)

# Parse the JSON response
data = response.json()

# Extract the price from the response
price = data[crypto_symbol]["usd"]

# Print the price
print(f"The current price of {crypto_symbol.upper()} is ${price}")

In this example, we are retrieving the real-time price of Bitcoin (BTC) in USD. You can modify the crypto_symbol variable to retrieve the price of any other cryptocurrency supported by the CoinGecko API. Additionally, you can specify multiple symbols separated by commas in the ids parameter to retrieve prices for multiple cryptocurrencies in a single request.

The response from the CoinGecko API is in JSON format. By parsing the JSON response, you can extract the relevant data such as the price. In this example, we access the price using the crypto_symbol and the currency code (usd in this case).

Remember to install the requests library if you haven’t already done so. You can install it using pip with the command: pip install requests.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply