Search code examples
pythonjsonapidictionarybinance

Can't get the information from a URL api working with json?


I want to get api information from this url: https://api.binance.com/api/v1/ticker/24hr I need to tell a symbol (ETHBTC) and get the lastprice.

import requests

binance = requests.get("https://api.binance.com/api/v1/ticker/24hr")
e = binance.json()
print(e['ETHBTC']['lastPrice'])

Error:

Traceback (most recent call last):
  File "C:\Users\crist\Documents\Otros\Programacion\Python HP\borrar.py", line 6, in <module>
    print(e['ETHBTC']['lastPrice'])
TypeError: list indices must be integers or slices, not str

Solution

  • Because you aren't specifying the pair you want in your request, the Binance API is returning details for all pairs in a list, like this:

    [
        { Pair 1 info },
        { Pair 2 info },
        { etc.        }
    ]
    

    So you'll need to either request only the details of the pair you want, or find the details of the pair you want in the list that you're already fetching.

    To request only the pair you want, you use Requests' URL parameters as an argument to your get request:

    myparams = {'symbol': 'ETHBTC'}
    binance = requests.get("https://api.binance.com/api/v1/ticker/24hr", params=myparams)
    e = binance.json()
    print(e['lastPrice'])
    

    Or, to find the pair you want in the list you're already fetching you can loop through the list. The first option is the way to go unless you want to look at lots of different pairs.

    binance = requests.get("https://api.binance.com/api/v1/ticker/24hr")
    e = binance.json()
    for pair in e:
        if pair['symbol'] == 'ETHBTC':
            print(pair['lastPrice'])