Skip to content

Chapter 10 · httpx Introduction and Sync API ​

Chapter goals: Understand httpx's design philosophy, master the basic usage of sync clients, and compare similarities and differences with requests.

10.1 Why Choose httpx ​

requests is the de facto standard for sync HTTP libraries, but it has a fundamental limitation: no async support. As asyncio became popular in the Python ecosystem, httpx emerged:

python
# requests — sync only
import requests
resp = requests.get('https://api.github.com')  # blocks the entire thread

# httpx — shared API for sync and async
import httpx
# Sync usage (almost identical to requests)
resp = httpx.get('https://api.github.com')
# Async usage
async with httpx.AsyncClient() as client:
    resp = await client.get('https://api.github.com')

10.2 Installation and Basic Usage ​

bash
pip install httpx
python
import httpx

# Simplest GET request
resp = httpx.get('https://httpbin.org/get')
print(resp.status_code)    # 200
print(resp.json())         # auto-parsed JSON

# POST request
resp = httpx.post(
    'https://httpbin.org/post',
    json={'key': 'value'}
)

10.3 API Comparison with requests ​

Operationrequestshttpx
GETrequests.get(url)httpx.get(url)
POST JSONrequests.post(url, json=data)httpx.post(url, json=data)
Query paramsrequests.get(url, params={})httpx.get(url, params={})
Headersheaders={'Key': 'Val'}headers={'Key': 'Val'}
Timeouttimeout=10timeout=10.0
Sessionrequests.Session()httpx.Client()

Key Difference

httpx's timeout only accepts floats (seconds); requests accepts integers or tuples (connect, read).

10.4 Client Objects and Connection Pools ​

python
import httpx

# Create a persistent client (reuse connection pool)
with httpx.Client() as client:
    # All requests share the connection pool
    resp1 = client.get('https://api.github.com/users/octocat')
    resp2 = client.get('https://api.github.com/users/torvalds')
    
    # Check connection reuse
    print(client.transport)  # HTTPConnectionPool instance

10.5 Chapter Summary ​

  • httpx provides both sync and async APIs, highly compatible with requests API style;
  • Use httpx.Client() to manage connection pools, replacing requests' Session;
  • Learning httpx costs almost nothing for developers familiar with requests.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is the core difference between httpx and requests?

2. What is the relationship between httpx.Client() and requests.Session()?

3. What type is the timeout parameter for httpx.get()?

4. What is the main work when migrating from requests to httpx?

🛠️ Hands-on Practice ​

  1. Use httpx sync API to implement the same GitHub user lookup as requests.
  2. Compare connection reuse between httpx.Client() and creating multiple httpx.get() calls.
  3. Implement a function that sends the same request with both requests and httpx, comparing execution time.

Next chapter: Async Client AsyncClient