Sobes.tech
Middle

How to make 10 requests to an external API in parallel and return the result?

sobes.tech AI

Answer from AI

For parallel execution of 10 requests to an external API in Python, it is convenient to use the asyncio module together with aiohttp. This allows you to run requests asynchronously without blocking the main thread.

Example:

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [f'https://api.example.com/data/{i}' for i in range(10)]
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
    return results

if __name__ == '__main__':
    results = asyncio.run(main())
    for i, content in enumerate(results):
        print(f'Result {i}:', content[:100])  # print first 100 characters of the response

This approach allows you to efficiently perform many requests simultaneously, saving network wait time.