'TypeError: list indices must be integers or slices, not str API, Json in Python

I am trying to get data from API but facing an error. I need block height from this API.

import requests
import json


fetch_json_net = requests.get('https://api.minaexplorer.com/blocks?limit=1')
blk_height_net = fetch_json_net.json()["blocks"]["blockHeight"]
print(blk_height_net)


Solution 1:[1]

Here is the JSON data. You're attempting to get listed in a dictionary. It will not work if you attempt the slicing approach to get data from list. To obtain data from a dictionary, use the get method with key. Here's the code for obtaining data for "blockHeight" for the first Element.

Method One:

import requests
import json

fetch_json_net = requests.get('https://api.minaexplorer.com/blocks?limit=1')
blk_height_net = fetch_json_net.json()["blocks"][0]["blockHeight"]
print(blk_height_net)
115919

Another Method:

import requests
import json


fetch_json_net = requests.get('https://api.minaexplorer.com/blocks?limit=1')
blk_height_net = fetch_json_net.json().get("blocks")[0].get('blockHeight')
print(blk_height_net)
115919

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MD Kawsar