1

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?

pipikej
  • 285
  • 3
  • 17

1 Answers1

3

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)
Ben
  • 305
  • 5
  • 12
Abinav R
  • 365
  • 2
  • 16