Home > Mobile >  HackerNews API extraction error - TypeError: list indices must be integers or slices, not str
HackerNews API extraction error - TypeError: list indices must be integers or slices, not str

Time:09-23

Trying to run this code to get the topstories from hacker news is giving me this error 'TypeError: list indices must be integers or slices, not str', the error is generated at

story = data['story']

from multiprocessing import context
from django.shortcuts import render
import requests

# Create your views here.
def index(request):
    #make an api call and save response
    url = f'https://hacker-news.firebaseio.com/v0/topstories.json'
    response = requests.get(url)
    data = response.json()
    story = data['story']
    context = {
        'story': story
    }
    return render(request, 'SyncNews/index.html', context)

What can I do to correct this error as I'm following a video showing a similar project but this error was not seen, I've also tried removing the '' but receive an error 'UnboundLocalError at / local variable 'story' referenced before assignment'

story = data['story']

CodePudding user response:

Your 'data' is a list of numbers, not a dictionary. Depending on whether you want to have one or more numbers from that list you can do one of such options:

# first number:
def index(request):
    ...
    data = response.json()
    story = data[0]
    context = {
        'story': story
    }
    return render(request, 'SyncNews/index.html', context)

# list of numbers:
def index(request):
    ...
    data = response.json()
    context = {
        'story': data
    }
    return render(request, 'SyncNews/index.html', context)
  • Related