How can i get all the pokémon types automatically with pokeapi?

Question:

I’m a beginner programmer, I’m adventuring with APIs and python.

I would like to know if I can get all types of pokémon withou passing a number as I did here:

import requests

name = "charizard"
url = f'https://pokeapi.co/api/v2/pokemon/%7Bname%7D'
poke_request = requests.get(url)
poke_request = poke_request.json()

types = poke_request['types'][0]['type']['name']

I tried doing some loops or passing variables but I always end up with some "slices" error.

If there’s a way to print the types inside a list, that would be great!

Asked By: Uemura

||

Answers:

PokeAPI has direct access to the pokemon types:

import requests                                                                                         
                                                                                                        
url = "https://pokeapi.co/api/v2/type/"                                                                 
poke_request = requests.get(url)                                                                        
types = poke_request.json()                                                                             
                                                                                                        
for typ in types["results"]:                                                                            
    print(typ)

EDIT:

You can save the names as a list using

names = [typ["name"] for typ in types["results"]]
Answered By: JustLearning

with the help of the user JustLearning I was able to adapt the solution to the scenario I wanted:

import requests                                                                                         
                                                                                                    
url = "https://pokeapi.co/api/v2/pokemon/charizard"                                                                 
poke_request = requests.get(url)                                                                        
types = poke_request.json()                                                                             

names = [typ["type"]["name"] for typ in types["types"]]

print(names)
Answered By: Uemura
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.