Python Mastery – From Basics to Brilliance / Asynchronous Programming

Async API requests

🌐 Async API Requests

Async API requests allow Python to send multiple API requests concurrently, so the program doesn't have to wait for one request to finish before starting another.

A common library for this is aiohttp.

πŸ“¦ Install

pip install aiohttp

πŸ“₯ Basic Async GET Request

import asyncio
import aiohttp

async def get_data():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.example.com/data") as response:
            data = await response.json()
            print(data)

asyncio.run(get_data())

Here:

async def        β†’ Async function
session.get()    β†’ Send API request
await            β†’ Wait for response without blocking
response.json()  β†’ Read JSON response

πŸš€ Multiple API Requests

import asyncio
import aiohttp

async def get_data(session, url):
    async with session.get(url) as response:
        return await response.json()

async def main():
    urls = [
        "https://api.example.com/1",
        "https://api.example.com/2",
        "https://api.example.com/3"
    ]

    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(
            *(get_data(session, url) for url in urls)
        )

        print(results)

asyncio.run(main())

⭐ Remember

Async API requests = Send multiple network requests efficiently without blocking while waiting for responses.