So I have been working on creating a mini pokedex using the poke api and I am stuck in a step.
This is what I have:
import requests
import json
import pandas as pd
pokemon_list = ["charizard", "gengar", "venusaur","golbat","gyarados","lapras", "dragonite", "infernape", "staraptor", "giratina"]
# Create empty lists to append all data:
name, height, weight = [],[],[]
# Get data from API
for pokemon in pokemon_list:
res = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}/")
pokedata = json.loads(res.text)
# Append data to the list:
name.append(pokedata["name"])
height.append(pokedata["height"])
weight.append(pokedata["weight"])
ddata = {"Name": name, "Height": height, "Weight": weight}
df_data = pd.DataFrame(ddata)
print(df_data)
and this is the TraceBack I am getting:
Traceback (most recent call last):
File "main.py", line 19, in <module>
pokedata = json.loads(res.text)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
P.S.: if I try to read just one pokemon instead of a list, it works fine, but whenever I try to use a list with the for loop, I get this error. Any help you guys can provide will be greatly appreciated.
CodePudding user response:
It turns out res.text
is 'Not Found'
in the failing case. Don't try to read the JSON if the result fails. FYI, debug yourself by print(res.text)
before the line that fails.
import requests
import json
import pandas as pd
pokemon_list = ["charizard", "gengar", "venusaur","golbat","gyarados","lapras", "dragonite", "infernape", "staraptor", "giratina"]
#Create empty lists to append all data:
name, height, weight = [],[],[]
#Get data from API
for pokemon in pokemon_list:
res = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}/")
if res.ok:
pokedata = res.json()
# Append data to the list:
name.append(pokedata["name"])
height.append(pokedata["height"])
weight.append(pokedata["weight"])
else:
print(f'{pokemon} not found')
ddata = {"Name": name, "Height": height, "Weight": weight}
df_data = pd.DataFrame(ddata)
print(df_data)
Output:
giratina not found
Name Height Weight
0 charizard 17 905
1 gengar 15 405
2 venusaur 20 1000
3 golbat 16 550
4 gyarados 65 2350
5 lapras 25 2200
6 dragonite 22 2100
7 infernape 12 550
8 staraptor 12 249