Uemura
Uemura

Reputation: 39

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

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!

Upvotes: 0

Views: 3427

Answers (2)

Uemura
Uemura

Reputation: 39

The user @JustLearning helped me out and 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)

Upvotes: 1

CrisPlusPlus
CrisPlusPlus

Reputation: 2312

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"]]

Upvotes: 2

Related Questions