HTTPX is an excellent HTTP client for Python that provides synchronous and asynchronous features. The examples below demonstrate a sync and async HTTPX client by comparing the elapsed time of performing four GET requests. The endpoint for each GET request has a four second response delay.
The synchronous example is shown below. Each GET request is performed sequentially therefore the total elapsed time is approximately 16 seconds.
import json
import time
import httpx
url = "https://httpbin.org/delay/4"
def example1():
"""Run synchronous example."""
tic = time.perf_counter()
with httpx.Client(timeout=20) as client:
for i in range(4):
response = client.get(url)
print("Result", i)
print(json.dumps(response.json(), indent=2), "\n")
toc = time.perf_counter()
print("Elapsed", toc - tic, "\n")
if __name__ == "__main__":
example1()
The asynchronous example is shown next. Since all four GET requests are performed simultaneously, the elapsed time is approximately 4 seconds.
import asyncio
import json
import time
import httpx
url = "https://httpbin.org/delay/4"
async def fetch(client: httpx.AsyncClient, url: str) -> dict:
"""Fetch function used for async example."""
response = await client.get(url)
return response.json()
async def example2():
"""Run asynchronous example."""
tic = time.perf_counter()
async with httpx.AsyncClient(timeout=20) as client:
tasks = [fetch(client, url) for _ in range(4)]
results = await asyncio.gather(*tasks)
for i in range(len(results)):
print("Result", i)
print(json.dumps(results[i], indent=2), "\n")
toc = time.perf_counter()
print("Elapsed", toc - tic)
if __name__ == "__main__":
asyncio.run(example2())
More information about HTTPX is available at https://www.python-httpx.org.
Gavin Wiggins © 2025
Made on a Mac with Genja. Hosted on GitHub Pages.