Search code examples
pythonpython-requestspokeapi

Accessing pokeapi - taking a long time


I want to get a list of names of pokemon from the first 150 that have a hp less than a particular value.

Here's what I've got so far:

def get_pokemon_with_similar_hp(max_hp):
    pokemon_names = []
    poke_data = []
    for i in range(1, 151):
        api_url = f"https://pokeapi.co/api/v2/pokemon/{i}"
        pokemon_response = requests.get(api_url)
        pokemon_data = pokemon_response.json()
        poke_data.append(pokemon_data)
    
    for j in range(0, 150):
        if poke_data[j]['stats'][0]['base_stat'] < max_hp:
                pokemon_names.append(poke_data[j]['name'])
    return pokemon_names   

This works, and gives me the data I want, but it's currently taking 8.49 s to process and send through to my frontend. Is there a way of improving my code to speed things up? Many thanks in advance :)


Solution

  • According to the API documentation you can use GraphQL query, so you can do this in one request. E.g.:

    import requests
    
    graphql_url = "https://beta.pokeapi.co/graphql/v1beta"
    
    
    # https://beta.pokeapi.co/graphql/console/
    payload = {
        "operationName": "samplePokeAPIquery",
        "query": r"query samplePokeAPIquery($maxhp: Int) {pokemon_v2_pokemon(where: {pokemon_v2_pokemonstats: {base_stat: {_lt: $maxhp}}}) {id name}}",
        "variables": {"maxhp": 100},
    }
    
    data = requests.post(graphql_url, json=payload)
    print(json.dumps(data.json(), indent=4))
    

    Prints:

    {
        "data": {
            "pokemon_v2_pokemon": [
                {
                    "id": 1,
                    "name": "bulbasaur"
                },
                {
                    "id": 2,
                    "name": "ivysaur"
                },
                {
                    "id": 3,
                    "name": "venusaur"
                },
    
    ...