Learn / Advanced / Lesson 8

Project: speed up API calls

20 min Tested on Python 3.15Updated By
In short

When a program calls many APIs one after another, almost all the time is spent waiting. Running the calls concurrently — with ThreadPoolExecutor for existing code or asyncio with httpx for new code — cuts the total to roughly the slowest call. Production versions add a concurrency limit, timeouts and retries.

The scenario

You need free cash flow (cash from operations minus capital expenditure) for a list of companies, and every company needs its own API request. The original version of this case study used a finance library that has since stopped working, so here we use a simulated API with realistic delays — the techniques are exactly the same for any real API.

fake_api.py
import random
import time

DATA = {
    "NEM": (2_870, 1_570), "FCX": (5_160, 4_810), "BHP": (20_670, 9_270),
    "RIO": (15_600, 9_620), "VALE": (9_770, 6_400), "AAL": (3_960, 3_150),
}


def get_cash_flow(ticker: str) -> dict:
    """Pretend API: 0.5–1.0 s per call, like a real network round trip."""
    time.sleep(random.uniform(0.5, 1.0))
    operations, capex = DATA[ticker]
    return {"ticker": ticker, "operations": operations, "capex": capex}


def free_cash_flow(row: dict) -> int:
    return row["operations"] - row["capex"]

Version 1: one by one

sequential.py · run on your computer
import time
from fake_api import DATA, free_cash_flow, get_cash_flow

start = time.perf_counter()
rows = [get_cash_flow(t) for t in DATA]
for row in rows:
    print(f"{row['ticker']:<5}{free_cash_flow(row):>8,}")
print(f"took {time.perf_counter() - start:.1f}s")
Output
NEM     1,300
FCX       350
BHP    11,400
RIO     5,980
VALE    3,370
AAL       810
took 4.5s

Version 2: a thread pool

threaded.py · run on your computer
import time
from concurrent.futures import ThreadPoolExecutor
from fake_api import DATA, free_cash_flow, get_cash_flow

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=8) as pool:
    rows = list(pool.map(get_cash_flow, DATA))
for row in rows:
    print(f"{row['ticker']:<5}{free_cash_flow(row):>8,}")
print(f"took {time.perf_counter() - start:.1f}s")
Output
NEM     1,300
FCX       350
BHP    11,400
RIO     5,980
VALE    3,370
AAL       810
took 1.0s

Three changed lines, same results, about four times faster. pool.map keeps the original order, so the report doesn't change. This is the quickest win when your code already uses a blocking library such as requests.

Version 3: asyncio

async_version.py · run on your computer
import asyncio
import random
import time
from fake_api import DATA, free_cash_flow


async def get_cash_flow(ticker: str, limit: asyncio.Semaphore) -> dict:
    async with limit:
        await asyncio.sleep(random.uniform(0.5, 1.0))
        operations, capex = DATA[ticker]
        return {"ticker": ticker, "operations": operations, "capex": capex}


async def main() -> None:
    limit = asyncio.Semaphore(10)
    start = time.perf_counter()
    rows = await asyncio.gather(*(get_cash_flow(t, limit) for t in DATA))
    for row in rows:
        print(f"{row['ticker']:<5}{free_cash_flow(row):>8,}")
    print(f"took {time.perf_counter() - start:.1f}s")


asyncio.run(main())
Output
NEM     1,300
FCX       350
BHP    11,400
RIO     5,980
VALE    3,370
AAL       810
took 1.0s
VersionTime for 6 callsBest when
Sequential~4.5 s (sum of all calls)A handful of calls, simplicity matters most
Thread pool~1 s (the slowest call)Existing code with requests or SDKs
asyncio~1 s (the slowest call)Hundreds of calls, async libraries, web servers

Making it production-ready

real_api.py
import asyncio

import httpx


async def fetch_json(client: httpx.AsyncClient, url: str, retries: int = 3) -> dict:
    for attempt in range(1, retries + 1):
        try:
            response = await client.get(url, timeout=10)
            response.raise_for_status()
            return response.json()
        except (httpx.TransportError, httpx.HTTPStatusError) as err:
            if attempt == retries:
                raise
            await asyncio.sleep(2 ** attempt)     # back off: 2 s, 4 s...
    raise RuntimeError("unreachable")


async def fetch_all(urls: list[str], max_concurrent: int = 5) -> list[dict]:
    limit = asyncio.Semaphore(max_concurrent)
    async with httpx.AsyncClient() as client:
        async def guarded(url: str) -> dict:
            async with limit:
                return await fetch_json(client, url)
        return await asyncio.gather(*(guarded(u) for u in urls))
  • One shared AsyncClient reuses connections instead of opening a new one per request.
  • timeout=10 stops one hanging server from freezing the whole job.
  • Retries with exponential back-off survive brief outages without hammering the server.
  • A Semaphore respects the API's rate limit. Check the provider's documented limits.

Practice

Compute free cash flow for the report. Given rows = [{"ticker": "NEM", "operations": 2870, "capex": 1570}, {"ticker": "FCX", "operations": 5160, "capex": 4810}, {"ticker": "BHP", "operations": 20670, "capex": 9270}], print each ticker with its free cash flow like NEM: 1300, then the ticker with the highest free cash flow.

Expected output:
NEM: 1300
FCX: 350
BHP: 11400
BHP
Your code

Quick check

1. Six API calls take 0.5–1.0 s each. Run concurrently, the total is about...

2. Why add a Semaphore when calling an API?

3. Your code uses requests everywhere. The quickest speed-up is...

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →