A Real-World Problem: When Requests Runs Out of Steam
If you’ve ever written a Python script to call an API or scrape data, chances are you’ve typed import requests. It is straightforward, memorable, and has accompanied an entire generation of developers. However, when switching to asynchronous frameworks like FastAPI or needing to scrape 500 web pages concurrently, an immediate bottleneck arises: requests is a synchronous, blocking I/O library.
What does this mean? The script sends a request, blocks the execution thread, and waits for the server to return 200 OK before firing the second one. One hundred requests taking 300ms each will waste 30 full seconds just waiting around. Using threading consumes excess RAM and risks race conditions. Moving to aiohttp introduces cumbersome syntax and complicated session management that breaks familiar habits. More importantly, requests still lacks support for HTTP/2.
That is why HTTPX has rapidly become the top replacement. It retains 95% of Requests’ familiar API while bringing two heavyweight features to the table: AsyncClient for asynchronous programming and native HTTP/2 support right out of the box.
Three Key Differences in HTTPX
Before diving into the code, let’s quickly review what HTTPX does better than its predecessor:
- Nearly Identical API to Requests: You still use
httpx.get(),httpx.post(), passheadersorjson, and parse data withresponse.json(). You can migrate libraries in under 5 minutes without learning from scratch. - Native Async/Await Support: It provides
httpx.AsyncClient, running seamlessly withasyncioand AnyIO. You can fire hundreds of network requests concurrently using the resources of just a single thread. - HTTP/2 Protocol Support: Instead of opening a new TCP connection for every request (incurring a 3-way handshake with 30–50ms latency), HTTP/2 multiplexes multiple parallel requests/responses over a single connection.
Hands-on: Mastering HTTPX from Basics to Advanced
Step 1: Installing the Library
The standard HTTPX package only includes HTTP/1.1 support. To enable HTTP/2, install the optional h2 dependency using:
# Standard installation
pip install httpx
# Installation with HTTP/2 support (recommended)
pip install httpx[http2]
Step 2: Making Familiar Synchronous Requests
For simple automation scripts, you can call top-level module functions just like before:
import httpx
# Send a GET request with query params
res = httpx.get("https://httpbin.org/get", params={"lang": "python", "tool": "httpx"})
print("Status code:", res.status_code)
print("Your IP:", res.json()["origin"])
# Send a POST request with a JSON body
payload = {"user": "itfromzero", "role": "developer"}
post_res = httpx.post("https://httpbin.org/post", json=payload)
print("Sent payload:", post_res.json()["json"])
Step 3: Reusing Connections with Client (Connection Pooling)
Avoid calling httpx.get() repeatedly in loops. With every standalone call, Python performs the TCP and TLS handshakes from scratch, which is highly inefficient. Instead, use httpx.Client within a with block:
import httpx
base_url = "https://jsonplaceholder.typicode.com"
# Initialize a client sharing a connection pool, with a default timeout
with httpx.Client(base_url=base_url, timeout=5.0) as client:
users = client.get("/users").json()
posts = client.get("/posts").json()
print(f"Successfully fetched {len(users)} users and {len(posts)} posts.")
This significantly reduces latency on subsequent requests, particularly when interacting with HTTPS APIs.
Step 4: Boosting Performance with AsyncClient and asyncio
This is where HTTPX truly shines. Suppose you need to fetch 10 records from an API, each taking about 300ms in server response time. Running sequentially would take a full 3 seconds. By using AsyncClient, the total elapsed time drops to roughly that of the single slowest request (around 350ms):
import asyncio
import time
import httpx
async def fetch_post(client: httpx.AsyncClient, post_id: int) -> str:
url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"
res = await client.get(url)
return res.json()["title"]
async def main():
start = time.perf_counter()
async with httpx.AsyncClient(timeout=10.0) as client:
# Create a list of 10 concurrent coroutines
tasks = [fetch_post(client, i) for i in range(1, 11)]
titles = await asyncio.gather(*tasks)
elapsed = time.perf_counter() - start
print(f"Successfully retrieved {len(titles)} posts in {elapsed:.2f} seconds.")
asyncio.run(main())
Performance improves dramatically while maintaining clean, readable syntax without wrestling with thread pools or multiprocessing.
Step 5: Enabling HTTP/2 with a Single Parameter
To take advantage of multiplexing on servers supporting HTTP/2 (such as Cloudflare or Google APIs), simply set http2=True when instantiating the client:
import httpx
with httpx.Client(http2=True) as client:
res = client.get("https://www.cloudflare.com")
print("HTTP version returned by server:", res.http_version) # Output: HTTP/2
If the remote server does not support HTTP/2, HTTPX automatically falls back to HTTP/1.1 without interrupting your application.
Step 6: Handling Network Errors and Checking Status Codes Gracefully
Writing production-grade code requires comprehensive exception handling. HTTPX cleanly differentiates between network errors and HTTP-level status errors:
import httpx
try:
with httpx.Client(timeout=3.0) as client:
res = client.get("https://httpbin.org/status/404")
res.raise_for_status() # Raises HTTPStatusError if status >= 400
except httpx.HTTPStatusError as exc:
print(f"Server returned error code {exc.response.status_code} at URL: {exc.request.url}")
except httpx.TimeoutException:
print("Request timed out after 3 seconds.")
except httpx.RequestError as exc:
print(f"Network error or failed DNS resolution: {exc}")
When developing web scraping bots or processing raw HTML/text API payloads, parsing data with regex is very common. Rather than manually testing regex in Python with tedious print statements and debug logs, you can visit toolcraft.app/en/tools/developer/regex-tester to test patterns directly in your browser before pasting them into your source code.
Conclusion
For modern projects—especially those built with FastAPI or microservices demanding high-performance I/O—HTTPX is a worthwhile upgrade. It lets you retain the developer-friendly ergonomics of Requests while unlocking both native Async/Await and modern HTTP/2 capabilities.

