DEV Community

artydev
artydev

Posted on

Async Requests in Python can be rather fasts

When it comes to make multiple concurrent requests, doing it synchronously can't be a solution.

Here is a way to do it using aiohttp and asyncio AsyncIO IOHTTP.

import aiohttp
import asyncio
import time

start_time = time.time()

async def get_pokemon(session, url):
    async with session.get(url) as resp:
        pokemon = await resp.json()
        return pokemon['name']

async def make_async_requests():
    async with aiohttp.ClientSession() as session:
        tasks = []
        for number in range(1, 1000):
            url = f'https://pokeapi.co/api/v2/pokemon/{number}'
            tasks.append(asyncio.ensure_future(get_pokemon(session, url)))

        original_pokemon = await asyncio.gather(*tasks)
        for pokemon in original_pokemon:
            print(pokemon)

def main () :
    print("\nStart 1000 requests.....................")
    asyncio.run(make_async_requests())
    print("\nEnd.......................")
    print("\n---Requests completed in  %s seconds ---" % (time.time() - start_time)) 

main ()
Enter fullscreen mode Exit fullscreen mode
---Requests completed in  1.6424751281738281 seconds ---
Enter fullscreen mode Exit fullscreen mode

Not bad isn't it ?

Top comments (0)