httpx – send multiple requests from dynamic list

Question:

I would like to send multiple request at once to the API. But I do not know how to trigger the requests because part of the URL is loaded from dynamic list which can have different length every time.

Right now I am looping through the list and sending the request one by one but that is kinda slow.

for url_param in parameters:
    r = httpx.get(f"http://my-api/{url_param}")

Is there any way to trigger all the requests at once with httpx and asyncio?

Asked By: pipikej

||

Answers:

Load all the request in an array and send them together in an async client session

import asyncio
import httpx

async def do_tasks():
    async with httpx.AsyncClient() as client:
        tasks = [client.get(f"http://my-api/{url_param}") for url_param in parameters]
        result = await asyncio.gather(*tasks)
Answered By: Abinav R