Ethereum: Get data from list of API response

  • Post category:cryptocurrency

Retrieving Data from an Ethereum API List

In this article, we’ll explore how to access data from a list of API responses and extract the relevant information.

Overview of the Task

The task involves creating a Python script that takes a list of API response objects as input. Each object contains two key-value pairs: symbol and lastPrice. Our goal is to print out only the lastPrice values, assuming they are the prices we’re interested in retrieving.

Prerequisites

Before proceeding, make sure you have:

  • Python 3.x is installed on your system.

  • An API key or access token for Ethereum, which can be obtained from various sources such as [CoinGecko]( or [Binance API](

Script Implementation








Ethereum: Get data from list of API response

Import the required libraries

import requests


Define a list of API response objects

price_list = [

{ 'symbol': 'ETHBTC', 'lastPrice': '0.03574700'}, #ETHBTC

{ 'symbol': 'BTCUSDT', 'lastPrice': '57621.08000000'} #BTCUSDT

]


Use the requests library to send a GET request to the API endpoint

def get_api_response(data, endpoint):

"""Send a GET request to the API endpoint and return the response data.

response = requests . get ( endpoint , params = data )

return response . json ( )


Extract the lastPrice values ​​​from each API response object

for item in price_list:

print(f"Last Price for {item['symbol']}: {item['lastPrice']}")


Use a list comprehension to extract and print only the lastPrice values

last_prices = [item['lastPrice'] for item in price_list if 'BTCUSDT' in item['symbol']]

print("Last Prices:")

for price in last_prices:

print(price)

How ​​​it Works

  • The script imports the requests library, which allows us to send HTTP requests to an API endpoint.

  • We define a list of API response objects (price_list) containing two key-value pairs: symbol and lastPrice.

  • We use a nested function called get_api_response() that sends a GET request to the specified API endpoint using the requests library. The endpoint parameter is passed as a keyword argument, which contains the base URL for the API endpoint.

  • Within the get_api_response() function, we parse the JSON response data using the json() method.

  • We then extract the lastPrice values ​​​from each API response object and print them to the console using nested loops and list comprehensions.

  • Finally, we use a list comprehension to filter out any items where BTCUSDT is not present in the symbol.

Sample Output

Last Prices:

57621.08000000

0.03574700

Last Prices:

57621.08000000

This script provides a simple way to retrieve data from an Ethereum API list and extract specific values, making it useful for various applications such as data analysis or web scraping.

ETHEREUM HISTORICAL BINANCE